首页 > 解决方案 > .Net Core:仅加密为 az 字符

问题描述

我正在使用以下加密类

public static class Extensions
{
    static string key = "jdsg432387#";
    static byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
    public static string Encrypt(this string plainText)
    {
        byte[] EncryptKey = { };
        EncryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByte = Encoding.UTF8.GetBytes(plainText);
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(EncryptKey, IV), CryptoStreamMode.Write);
        cStream.Write(inputByte, 0, inputByte.Length);
        cStream.FlushFinalBlock();
        return Convert.ToBase64String(mStream.ToArray());
    }

    public static string Decrypt(this string encryptedText)
    {
        byte[] DecryptKey = { };
        byte[] inputByte = new byte[encryptedText.Length];

        DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByte = Convert.FromBase64String(encryptedText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByte, 0, inputByte.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }
}

但是它会在加密结果字符串中生成特殊字符(例如 +、=)
我如何将加密结果字符串限制为仅 az 字符?

标签: asp.net-core.net-core

解决方案


您可以将字符串转换为十六进制

public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
     Byte[] stringBytes = encoding.GetBytes(input);
    StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
    foreach (byte b in stringBytes)
     {
         sbBytes.AppendFormat("{0:X2}", b);
    }
    return sbBytes.ToString();
}

并将十六进制解密为字​​符串

public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
     int numberChars = hexInput.Length;
    byte[] bytes = new byte[numberChars / 2];
     for (int i = 0; i < numberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
     }
     return encoding.GetString(bytes);
}

推荐阅读