Padding is invalid and cannot be removed come this error ..
My code is
public static byte[] EncryptStringToBytes(string str, byte[] key) { byte[] encrypted;
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) {
key =aes.Key; aes.GenerateIV(); // The get method of the 'IV' property of the 'SymmetricAlgorithm' automatically generates an IV if it is has not been generate before.
aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7;
using (MemoryStream msEncrypt = new MemoryStream()) { msEncrypt.Write(aes.IV, 0, aes.IV.Length); ICryptoTransform encoder = aes.CreateEncryptor(); using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encoder, CryptoStreamMode.Write)) using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(str); } encrypted = msEncrypt.ToArray(); } }
return encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] key) { string decrypted ; using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { // Setting a key size disposes the previously-set key. // Setting a key size will generate a new key. // Setting a key size is redundant if a key going to be set after this statement.
key = aes.Key; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7;
//ICryptoTransform decoder = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream msDecryptor = new MemoryStream(cipherText)) { byte[] IV = new byte[16]; msDecryptor.Read(IV,0, 16); aes.IV = IV; //ICryptoTransform decoder = aes.CreateDecryptor(aes.Key,aes.IV ); ICryptoTransform decoder = aes.CreateDecryptor(); using (CryptoStream csDecryptor = new CryptoStream(msDecryptor, decoder, CryptoStreamMode.Read)) using (StreamReader srReader = new StreamReader(csDecryptor)) {
//csDecryptor.FlushFinalBlock(); decrypted = srReader.ReadToEnd();
} } } return decrypted; }
please verify code and help me fast !!!!