My code used to work before when I used RijndaelManaged. Since its obsolete and suggest us to AES.
I change the code and now I get the error 'Padding is invalid and cannot be removed'.
Below is my code:
C#
public static string DecryptStringAES(string encryptedText, string key)
{
var keybytes = Encoding.UTF8.GetBytes(key);
var iv = keybytes;
var encryptStringToBytes = EncryptStringToBytes_Aes(encryptedText, keybytes, iv);
// Decrypt the bytes to a string. here encryptStringToBytes is byte[80]
var roundtrip = DecryptStringFromBytes_Aes(encryptStringToBytes, keybytes, iv);
//DECRYPT FROM CRIPTOJS
var encrypted = Convert.FromBase64String(roundtrip);
//here encryptStringToBytes is byte[48]
//This Line throws the exception --Padding is invalid and cannot be removed
var id = DecryptStringFromBytes_Aes(encrypted, keybytes, iv);
return id;
}
private static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV");
string plaintext = null;
try
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CFB;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
string err = ex.Message;
throw;
}
return plaintext;
}
private static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV");
byte[] encrypted;
try
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CFB;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
}
catch (Exception ex)
{
string er = ex.Message;
throw ex;
}
return encrypted;
}
Naimish MakwanaRank #324 · 7.7K reputationPosted Oct 15, 2024, 10:17 AM EDT
The error “Padding is invalid and cannot be removed” typically occurs when the decryption process encounters an issue with the padding of the encrypted data. Here are a few things to check and adjust in your code:
Ensure Consistent Padding and Cipher Mode: Make sure that both the encryption and decryption processes use the same padding and cipher mode. In your code, you are using
PaddingMode.PKCS7andCipherMode.CFB, which is consistent.Initialization Vector (IV): The IV should be unique and random for each encryption operation. Using the key as the IV is not recommended. Instead, generate a random IV for each encryption and pass it along with the ciphertext.
Base64 Encoding/Decoding: Ensure that the data is correctly encoded and decoded when converting between strings and byte arrays.
Here’s an updated version of your code with these considerations:
public static string DecryptStringAES(string encryptedText, string key) { var keybytes = Encoding.UTF8.GetBytes(key); var iv = new byte; // Ensure IV is 16 bytes for AES Array.Copy(keybytes, iv, Math.Min(iv.Length, keybytes.Length)); var encryptStringToBytes = EncryptStringToBytes_Aes(encryptedText, keybytes, iv); // Decrypt the bytes to a string. Here encryptStringToBytes is byte var roundtrip = DecryptStringFromBytes_Aes(encryptStringToBytes, keybytes, iv); // DECRYPT FROM CRIPTOJS var encrypted = Convert.FromBase64String(roundtrip); // Here encryptStringToBytes is byte // This Line throws the exception --Padding is invalid and cannot be removed var id = DecryptStringFromBytes_Aes(encrypted, keybytes, iv); return id; } private static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV) { if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException(nameof(cipherText)); if (Key == null || Key.Length <= 0) throw new ArgumentNullException(nameof(Key)); if (IV == null || IV.Length <= 0) throw new ArgumentNullException(nameof(IV)); string plaintext = null; try { using (Aes aesAlg = Aes.Create()) { aesAlg.Mode = CipherMode.CFB; aesAlg.Padding = PaddingMode.PKCS7; aesAlg.Key = Key; aesAlg.IV = IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } } } catch (Exception ex) { string err = ex.Message; throw; } return plaintext; } private static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV) { if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException(nameof(plainText)); if (Key == null || Key.Length <= 0) throw new ArgumentNullException(nameof(Key)); if (IV == null || IV.Length <= 0) throw new ArgumentNullException(nameof(IV)); byte[] encrypted; try { using (Aes aesAlg = Aes.Create()) { aesAlg.Mode = CipherMode.CFB; aesAlg.Padding = PaddingMode.PKCS7; aesAlg.Key = Key; aesAlg.IV = IV; ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } } catch (Exception ex) { string er = ex.Message; throw; } return encrypted; }Try these adjustments and see if they resolve the padding issue. If the problem persists, double-check the data being encrypted and decrypted to ensure it matches expected formats.
Thanks
Istudent RanaRank #4,270 · 354 reputationPosted Oct 15, 2024, 12:22 PM EDT
adding feedback size to 128 resolve the issue.
aesAlg.FeedbackSize = 128;