0

i am using rijndeal to encrypt and decrypt some data! but it gives me this error :

Padding is invalid and cannot be removed.

i searched much but nothing help me to solve this error! tis is my encrypt/decrypt codes:

public string Encrypt(string text)
    {

        mainRM = new System.Security.Cryptography.RijndaelManaged();
        mainRM.BlockSize = 256;
        mainRM.KeySize = 256;
        memorystream = new System.IO.MemoryStream();
        ICryptoTransform icrypt = mainRM.CreateEncryptor(key, iv);
        CryptoStream cryptstream = new CryptoStream(memorystream, icrypt, CryptoStreamMode.Write);
        cryptstream.FlushFinalBlock();
        System.IO.StreamWriter sw = new System.IO.StreamWriter(cryptstream);
        sw.Write(text);
        return Convert.ToBase64String(memorystream.ToArray());
    }

    public string Decrypt(string CryptedText)
    {
        string custinfo;
        System.IO.StreamReader streamreader;
        mainRM = new RijndaelManaged();
        mainRM.BlockSize = 256;
        mainRM.KeySize = 256;
        memorystream = new System.IO.MemoryStream(Convert.FromBase64String(CryptedText));
        ICryptoTransform icrypt = mainRM.CreateDecryptor(key, iv);
        memorystream.Position = 0;
        CryptoStream cryptstream = new CryptoStream(memorystream, icrypt, CryptoStreamMode.Read);
        cryptstream.FlushFinalBlock();
        streamreader = new System.IO.StreamReader(cryptstream);
        custinfo = streamreader.ReadToEnd();
        return custinfo;
    }

can anyone help me?

1 Answers1

0

Set the decryption side to no padding. Decrypt and look at what you get added to the end of your plaintext. That will tell you what padding the encrypting side is adding. Change the encryption side to explicitly set that padding and change the decryption side to explicitly expect the same padding.

Alternatively set both to PKCS7 (aka PKCS5) padding. You need to have the padding the same at both sides.

rossum
  • 15,344
  • 1
  • 24
  • 38