BadPaddingException - Encrypt in C#, decrypt in Java
843811May 15 2009 — edited May 15 2009Hello Everyone I am new to this forum and new at decryption.
I am trying to decrypt a file in Java which was encrypted in C# using Rijndael/CBC/PKCS7 for 256-bit AES. I did not write the C# that does the encryption, I just know the algorithm/mode/padding. I take in data through the web server and I keep getting the following exception:
javax.crypto.BadPaddingException: pad block corrupted
at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(Unknown Source)
at javax.crypto.Cipher.doFinal(DashoA13*..) at AESFileDecrypter.decrypt(AESFileDecrypter.java:57)
when the "doFinal(inpbytes)" method is called for the first byte[]. I am guessing this is a problem with the key or IV, although I was given the key for testing and the IV. This should be straight forward plug in the key and IV, but I am going crazy. I have the sample encrypted files on my file system for testing.
Thank you very much for any help you can provide.
---------------------------
//code in web server to call decryption method
private void sendBytes(FileInputStream fis, OutputStream os)throws Exception
{
//set the buffer size to send 4k segments of data
byte[] buffer = new byte[4096];
int bytes = 0;
//while there is still data to be sent keep looping and write the data
//to the output stream as the buffer is filled
try
{
while ((bytes = fis.read(buffer)) != -1)
{
buffer = aesFileDecrypter.decrypt(buffer);
os.write(buffer, 0, bytes);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
***keyStr is base64 encoded
//decryption class
public AESFileDecrypter(String keyStr)
{
try
{
Security.addProvider(new BouncyCastleProvider());
convertIvParameter();
key = new sun.misc.BASE64Decoder().decodeBuffer(keyStr);
//use the passed in Base64 decoded key to create a key object
decryptKey = new SecretKeySpec(key, "AES");
//specify the encryption algorithm
decryptCipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
//make a parameter object for the initialization vector (IV)
IvParameterSpec ivs = new IvParameterSpec(_defaultIv);
//initialize the decrypter to the correct mode, key used and IV
decryptCipher.init(Cipher.DECRYPT_MODE, decryptKey, ivs);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void convertIvParameter()
{
int[] iv = new int[] {11, 190, 165, 33, 68, 88, 11,
200, 245, 35, 68, 23, 60, 24, 223, 67};
_defaultIv = new byte[16];
for(int x = 0; x < _defaultIv.length; x++)
{
_defaultIv[x] = (byte)iv[x];
}
}
public static byte[] decrypt(byte[] inpBytes) throws Exception
{
//decrypt the byte passed in from the web server
return decryptCipher.doFinal(inpBytes);
}