错误AES - 标准SymmetricAlgorithm,“填充无效且无法删除”

时间:2017-07-21 15:21:02

标签: c# .net encryption aes

我正在使用AES - Standard SymmetricAlgorithm,加密和解密字符串。字符串正在成功加密,但是当涉及到解密时,编译器会给我一个例外,即

  

“填充无效,无法删除”。

我已经创建了一个用于测试的演示控制台应用程序,请看下面的代码。

主要方法:

static void Main(string[] args)
{
    var content = "5466160057107706";
    var key = "E546C8DF278CD5931069B522E695D4F2";

    var encrypted = EncryptString(content, key);
    Console.WriteLine(encrypted);
    var decrypted = DecryptString(encrypted, key);
    Console.WriteLine(decrypted);
    Console.ReadLine();
}

为加密添加的方法:

public static string EncryptString(string text, string keyString)
{
    var key = Encoding.UTF8.GetBytes(keyString);
    using (var aesAlg = Aes.Create())
    {
        using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
        {
            using (var msEncrypt = new MemoryStream())
            {
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(text);
                }
                var iv = aesAlg.IV;
                var decryptedContent = msEncrypt.ToArray();
                var result = new byte[iv.Length + decryptedContent.Length];
                Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);
                return Convert.ToBase64String(result);
            }
        }
    }
}

为解密添加的方法:

public static string DecryptString(string cipherText, string keyString)
{
    var fullCipher = Convert.FromBase64String(cipherText);
    var iv = new byte[16];
    var cipher = new byte[16];
    Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
    Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
    var key = Encoding.UTF8.GetBytes(keyString);
    using (var aesAlg = Aes.Create())
    {
        using (var decryptor = aesAlg.CreateDecryptor(key, iv))
        {
            string result;
            using (var msDecrypt = new MemoryStream(cipher))
            {
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (var srDecrypt = new StreamReader(csDecrypt))
                    {
                        result = srDecrypt.ReadToEnd();
                    }
                }
            }
            return result;
        }
    }
}

以下是DecryptString()方法中出现的错误捕捉:

enter image description here

有什么建议,如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

线索: var cipher = new byte[16];

为什么你假设你的密码只有16个字节?如果超过这个怎么办?

事实上,如果我运行这个程序并进行调试,我会发现你的密码是32个字节。

因此,以下2行更改使其有效:

var cipher = new byte[32];

Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length);

在任何情况下,您都需要动态确定密码的大小。