Reputation: 2139
I am trying to convert a BouncyCastle specific implementation to a generic one, but as I am still struggling with the basics, I have it hard to do.
This is the previous BC code that works:
public int decrypt(SecurityToken token, byte[] dataToDecrypt, int inputOffset,
int inputLength, byte[] output, int outputOffset) {
// Make new RijndaelEngine
RijndaelEngine engine = new RijndaelEngine(128);
// Make CBC blockcipher
BufferedBlockCipher bbc = new BufferedBlockCipher(
new CBCBlockCipher(engine));
// find right decryption key and right initialization vector
KeyParameter secret = new KeyParameter(
token.getRemoteEncryptingKey());
byte[] iv = token.getRemoteInitializationVector();
// initialize cipher for decryption purposes
bbc.init(false, new ParametersWithIV(secret, iv));
decryptedBytes = bbc.processBytes(dataToDecrypt, inputOffset,
inputLength, output, outputOffset);
decryptedBytes += bbc.doFinal(output, outputOffset+decryptedBytes);
return decryptedBytes;
}
and this is my humble try so far:
SecretKeySpec spec = new SecretKeySpec(
token.getRemoteEncryptingKey(),
"AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, spec, new IvParameterSpec(token.getRemoteInitializationVector()));
decryptedBytes = cipher.update(dataToDecrypt, inputOffset,
inputLength, output, outputOffset);
decryptedBytes += cipher.doFinal(output, outputOffset+decryptedBytes);
return decryptedBytes;
which gives
javax.crypto.BadPaddingException: Given final block not properly padded
and here is input to the function:
decrypt: dataToDecrypt.length=1088 inputOffset=0 inputLength=1088 output.length=16384 outputOffset=1180
decrypt: token.getRemoteEncryptingKey()=lBjgFjfR3IilCyT5AqRnXQ==
decrypt: token.getRemoteInitializationVector()=0JFEdkuW6pMo0cwfKdZa3w==
What am I missing?
E: input data
Upvotes: 2
Views: 1418
Reputation: 69339
Normally BadPaddingException
means that either:
The original plaintext wasn't padded using the padding algorithm you've suggested. So perhaps PKCS#5 wasn't used when the data was encrypted.
You've used the wrong key to decrypt. This results in the padding looking incorrect when the the decryption has completed.
Hopefully you can look at your environment and figure out if either of these is likely? Looking at your BouncyCastle code, I would assume you are using no padding at all. Try changing:
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
to:
cipher = Cipher.getInstance("AES/CBC/NoPadding");
Upvotes: 1