【问题标题】:c# AES decryption Hebrew letters display as question marksc# AES解密希伯来字母显示为问号
【发布时间】:2018-05-07 20:34:12
【问题描述】:

我有一个包含希伯来字母的字符串,
加密后,当我试图解密加密的字符串时,所有的希伯来字母都显示为问号(如 -> ??? ?? ??????)

这是我用来加密和解密的两种方法

 public static string Encrypt(string dectypted)
    {
        byte[] textbytes = ASCIIEncoding.ASCII.GetBytes(dectypted);
        AesCryptoServiceProvider encdec = new AesCryptoServiceProvider();
        encdec.BlockSize = 128;
        encdec.KeySize = 256;
        encdec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
        encdec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
        encdec.Padding = PaddingMode.PKCS7;
        encdec.Mode = CipherMode.CBC;

        ICryptoTransform icrypt = encdec.CreateEncryptor(encdec.Key, encdec.IV);

        byte[] enc = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length);
        icrypt.Dispose();

        return Convert.ToBase64String(enc) + Key;
    }

    public static string Decrypt(string enctypted)
    {
        byte[] encbytes = Convert.FromBase64String(enctypted);
        AesCryptoServiceProvider encdec = new AesCryptoServiceProvider();
        encdec.BlockSize = 128;
        encdec.KeySize = 256;
        encdec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
        encdec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
        encdec.Padding = PaddingMode.PKCS7;
        encdec.Mode = CipherMode.CBC;

        ICryptoTransform icrypt = encdec.CreateDecryptor(encdec.Key, encdec.IV);

        byte[] dec = icrypt.TransformFinalBlock(encbytes, 0, encbytes.Length);
        icrypt.Dispose();

        return ASCIIEncoding.ASCII.GetString(dec);
    }

谁能告诉我哪里出了问题以及为什么我得到的希伯来字母问号?
提前致谢

【问题讨论】:

  • 使用 UTF8,而不是 ASCII。
  • 请注意,ASCII 中的字符代码只有 7 位(值 0-127)。
  • 请注意Decrypt() 不会解密Encrypt() 的输出,因为您已将Key 附加到Base64 数据,因此它不再是有效的Base64。此外,正如@AndrewMorton 指出的那样,ASCII 仅包含 7 位,因此将其用于 Key 和 IV 将执行缩小转换。也许也可以使用 Base64。
  • @Trevor 是的,我知道,我稍后在程序中将其删减,我只是展示了我的代码。问题是(正如大家提到的)ascii 使用,我改为 utf8 并且它正在工作

标签: c# encryption


【解决方案1】:

ASCII 不能表示希伯来字符。它只能表示一组有限的拉丁字符和符号。 UTF8 可能是您要使用的编码。将您对 ASCIIEncoding.ASCII 的使用替换为 Encoding.UTF8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2013-11-26
    相关资源
    最近更新 更多