AES 解密在中文语言环境中失败,出现无效字符错误

AES decryption fails in chinese locale with invalid character error

我有以下代码:

private static string AesDecrypt(string text, string key)
    {
        var encoding = Encoding.Default;
        var aes = new RijndaelManaged
        {
            KeySize = 256,
            BlockSize = 256,
            Padding = PaddingMode.Zeros,
            Mode = CipherMode.CBC,
            Key = encoding.GetBytes(key)
        };

        text = encoding.GetString(Convert.FromBase64String(text));

        var iv = text;
        iv = iv.Substring(iv.IndexOf("-[--IV-[-", StringComparison.Ordinal) + 9);
        text = text.Replace("-[--IV-[-" + iv, "");

        text = Convert.ToBase64String(encoding.GetBytes(text));
        aes.IV = encoding.GetBytes(iv);

        using (var aesDecrypt = aes.CreateDecryptor(aes.Key, aes.IV))
        {
            var buffer = Convert.FromBase64String(text);

            var result = encoding.GetString(aesDecrypt.TransformFinalBlock(buffer, 0, buffer.Length));
            result = result.Substring(0, result.IndexOf(Convert.ToChar(0)));

            return result;
        }
    }

    private static string AesEncrypt(string text, string key)
    {
        var encoding = Encoding.Default;
        var aes = new RijndaelManaged
        {
            KeySize = 256,
            BlockSize = 256,
            Padding = PaddingMode.Zeros,
            Mode = CipherMode.CBC,
            Key = (encoding.GetBytes(key))
        };

        aes.GenerateIV();
        var iv = ("-[--IV-[-" + encoding.GetString(aes.IV));

        using (var aesEncrypt = aes.CreateEncryptor(aes.Key, aes.IV))
        {
            var buffer = encoding.GetBytes(text);

            return Convert.ToBase64String(encoding.GetBytes(encoding.GetString(aesEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)) + iv));
        }
    }

当通过具有英语(美国)区域设置的系统访问时,它工作正常。但是,一旦我在具有中文语言环境的系统中尝试它,它就会抛出以下错误:

Specified initialization vector (IV) does not match the block size for this algorithm.

Invalid character in a Base-64 string.

一些消息来源说我应该使用 Encoding.UTF8 或 Encoding.Unicode 来解决这个问题。我试过了,但还是出现了同样的错误。

看起来它更像是一个字符串解码问题,而不是像 Rawling 所说的加密问题。感谢您指出这一点。

无论如何,我没有使用 Encoding.Default、Encoding.UTF 或 Encoding.Unicode,而是尝试使用基于美国的编码(OEM 美国)解决了我的问题:

Encoding.GetEncoding(437);

https://msdn.microsoft.com/en-us/library/system.text.encoding(v=vs.110).aspx

再次感谢!