“填充无效,无法删除” - 这段代码有什么问题?

时间:2010-02-16 04:23:54

标签: c# .net encryption aes

每次运行并加密时,输出都是可变的,当我尝试解密时 我得到“填充无效,无法删除。”现在已经和它斗争了一两天,我不知所措。

    private static string strIV = "abcdefghijklmnmo"; //The initialization vector.
    private static string strKey = "abcdefghijklmnmoabcdefghijklmnmo"; //The key used to encrypt the text.

    public static string Decrypt(string TextToDecrypt)
    {
        return Decryptor(TextToDecrypt);
    }

    private static string Encryptor(string TextToEncrypt)
    {
        //Turn the plaintext into a byte array.
        byte[] PlainTextBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToEncrypt);            

        //Setup the AES providor for our purposes.
        AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider();
        aesProvider.Key = System.Text.Encoding.ASCII.GetBytes(strKey);
        aesProvider.IV = System.Text.Encoding.ASCII.GetBytes(strIV);
        aesProvider.BlockSize = 128;
        aesProvider.KeySize = 256;            
        aesProvider.Padding = PaddingMode.PKCS7;
        aesProvider.Mode = CipherMode.CBC;

        ICryptoTransform cryptoTransform = aesProvider.CreateEncryptor(aesProvider.Key, aesProvider.IV);            
        byte[] EncryptedBytes = cryptoTransform.TransformFinalBlock(PlainTextBytes, 0, PlainTextBytes.Length);
        return Convert.ToBase64String(EncryptedBytes);                        
    }

    private static string Decryptor(string TextToDecrypt)
    {
        byte[] EncryptedBytes = Convert.FromBase64String(TextToDecrypt);

        //Setup the AES provider for decrypting.            
        AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider();
        aesProvider.Key = System.Text.Encoding.ASCII.GetBytes(strKey);
        aesProvider.IV = System.Text.Encoding.ASCII.GetBytes(strIV);
        aesProvider.BlockSize = 128;
        aesProvider.KeySize = 256;            
        aesProvider.Padding = PaddingMode.PKCS7;
        aesProvider.Mode = CipherMode.CBC;

        ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor(aesProvider.Key, aesProvider.IV);
        byte[] DecryptedBytes = cryptoTransform.TransformFinalBlock(EncryptedBytes, 0, EncryptedBytes.Length);
        return System.Text.Encoding.ASCII.GetString(DecryptedBytes);
    }
}

1 个答案:

答案 0 :(得分:11)

在设置BlockSizeKeySize之前,您需要设置KeyIV。另外,您应该为每条消息生成一个随机IV,并注意ICryptoTransform实现IDisposable所以应该处理这些对象。