“Padding is invalid and cannot be removed” -Whats wrong with this code?

半腔热情 提交于 2019-12-19 09:51:09

问题


Every time I run this and encrypt, the output is variable, and when I attempt to decrypt I get "Padding is invalid and cannot be removed." Been fighting with this for a day or two now and I am at a loss.

    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:


You need to set the BlockSize and the KeySize before you set the Key and the IV. Additionally you should probably be generating a random IV for each message and note that ICryptoTransform implements IDisposable so these objects should be disposed.



来源:https://stackoverflow.com/questions/2270614/padding-is-invalid-and-cannot-be-removed-whats-wrong-with-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!