I have very curious problem by string decryption using the AES algorithm. My C# application sends encrypted data (strings) to the Java application. Even I use the same key string, the decryption leads into the Exception:
javax.crypto.BadPaddingException: Given final block not properly padded at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:810)
however only when length of the plain input text to encrypt (at C# side) exceeds 1393 characters... But if the length equals to 1393 characters, or is lesser than 1393 characters, it works fine.
Here is the C# codefor encryption:
private static string Encrypt(string textToEncrypt, string key)
{
try
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 0x80; // 256bit key
rijndaelCipher.BlockSize = 0x80;
byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[0x10];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
{
len = keyBytes.Length;
}
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
}
catch (Exception ex)
{
throw ex;
}
}
And a Java code for decryption:
public static String Decrypt(String text, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes = new byte[16];
byte[] b = key.getBytes("UTF-8");
int len = b.length;
if (len > keyBytes.length) {
len = keyBytes.length;
}
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
BASE64Decoder decoder = new BASE64Decoder();
byte[] results = cipher.doFinal(decoder.decodeBuffer(text));
return new String(results, "UTF-8");
}
I've tried replace the BASE64Decoder to Base64 codec from apache, but the result was the same... I will be grateful for any advice or idea. Thanks.
ReadandWritecalls, just a stream of bytes. - CodesInChaosrijndaelCipher.IV = keyBytes;- it opens up for a chosen-ciphertext attack which recovers the key! See here - Ebbe M. Pedersen