1

when i use this code to encrypt and decrypt i got an error said

Padding is invalid and cannot be removed.

any idea

public static class Crypto
{

    private static readonly byte[] initVectorBytes = Encoding.ASCII.GetBytes("tu89geji340t89u2");

    // This constant is used to determine the keysize of the encryption algorithm.
    private const int keysize = 256;

    public static string Encrypt(string plainText, string passPhrase)
    {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
        {
            byte[] keyBytes = password.GetBytes(keysize / 8);
            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                symmetricKey.Mode = CipherMode.CBC;
                using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            byte[] cipherTextBytes = memoryStream.ToArray();
                            return Convert.ToBase64String(cipherTextBytes);
                        }
                    }
                }
            }
        }
    }

    public static string Decrypt(string cipherText, string passPhrase)
    {
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
        {
            byte[] keyBytes = password.GetBytes(keysize / 8);
            using (RijndaelManaged symmetricKey = new RijndaelManaged())
            {
                symmetricKey.Mode = CipherMode.CBC;
                using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                {
                    using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
    }
}
Tarek Saied
  • 6,482
  • 20
  • 67
  • 111
  • Have you looked at this : http://stackoverflow.com/questions/23406135/error-rijndaelmanaged-padding-is-invalid-and-cannot-be-removed – PaulF Jun 18 '15 at 14:26
  • yes and it did not work – Tarek Saied Jun 18 '15 at 14:43
  • How long is the data you are encrypting/decrypting? – PaulF Jun 18 '15 at 15:03
  • Have you tried this _"The suggestions in other replys will sometimes work, by chance, but what you really need to do is set RijndaelAlg.Padding to PaddingMode.ISO10126, PaddingMode.PKCS7, or PaddingMode.ANSIX923. Any one of these 3 values should work, provided that you use the same value when encrypting and decrypting. Other values will work with some data, but not with all data. The above URL explains why."_ (from here https://social.msdn.microsoft.com/Forums/vstudio/en-US/d1788582-bf8c-43ec-a686-49647c359136/unexplained-cryptographicexception-padding-is-invalid?forum=netfxbcl) – PaulF Jun 18 '15 at 15:09
  • @PaulF about 10 numbers like "1234567890" – Tarek Saied Jun 18 '15 at 15:14
  • _"The block of data to be encrypted must be as long as the key - in your case 16 bytes. Since you did not get an exception during encryption, the implementation you used "somehow" filled the remaining 12 bytes. I would suggest that you do that yourself - add some 12 bytes to your data (could be a random amount of bytes), encrypt it, and after decrypting just throw away those extra bytes."_ (from here : http://www.codeproject.com/Questions/350156/RijndaelManaged-Padding-is-invalid) – PaulF Jun 18 '15 at 15:17

1 Answers1

1

I tried the following using your methods and it worked fine:

var passPhrase = "123456";
var e = Encrypt("testtesttesttest", passPhrase);
Console.WriteLine(e); // YEtSJshcn686ZO+JlEQ48ap/odhuvIGalbAT1XhinqQ=
var d = Decrypt(e, passPhrase);
Console.WriteLine(d); // testtesttesttest

This suggests that you're either passing a different passPhrase to Decrypt() to the one you passed to Encrypt(), or that you are somehow corrupting the ciphertext prior to decryption. (Are you perhaps calling Decrypt with the ciphertext and passphrase parameters reversed?)

It's also worth noting that essentially everything in the comments at the top of your code is wrong:

  • You're not passing any salt to PasswordDeriveBytes.
  • The size of the IV must be equal to the block size (16 bytes), it is unrelated to the key size used.
  • Passing a 16 character string through Encoding.ASCII.GetBytes() results in a 16 byte output, not 32 bytes. (This rather coincidentally means that your initVectorBytes is in fact the correct length for the IV).

Furthermore, PasswordDeriveBytes is deprecated and should not be used. You should be using Rfc2898DeriveBytes instead, and you should be using a proper salt value. The IV should also not be a static value, and definitely not one derived from an ASCII string!

Iridium
  • 23,323
  • 6
  • 52
  • 74
  • sorry i remove the old method without removing the comment – Tarek Saied Jun 18 '15 at 17:49
  • @tito11 Did you look at the rest of the answer? I couldn't reproduce the error you describe, suggesting the issue lies in the code you *haven't* shown. I suggest editing your question to show how you are using these methods, and that will actually exhibit the error if dropped into Visual Studio and run. (See: http://sscce.org/) – Iridium Jun 19 '15 at 06:28