我正在尝试将 BouncyCaSTLe 特定实现转换为通用实现,但由于我仍在努力学习基础知识,所以我很难做到。
这是以前有效的 BC 代码:
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;
}
这是我迄今为止的拙劣尝试:
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;
给出
javax.crypto.BadPaddingException: Given final block not properly padded
这里是函数的输入:
decrypt: dataToDecrypt.length=1088 inputOffset=0 inputLength=1088 output.length=16384 outputOffset=1180
decrypt: token.getRemoteEncryptingKey()=lBjgFjfR3IilCyT5AqRnXQ==
decrypt: token.getRemoteInitializationVector()=0JFEdkuW6pMo0cwfKdZa3w==
我错过了什么?
E:输入数据
最佳答案
通常 BadPaddingException
意味着:
原始明文未使用您建议的填充算法进行填充。因此,当数据被加密时,可能没有使用 PKCS#5。
您使用了错误的 key 进行解密。这会导致解密完成后填充看起来不正确。
希望您可以看看您的环境并弄清楚是否可能出现其中任何一种情况?查看您的 BouncyCaSTLe 代码,我假设您根本不使用填充。尝试更改:
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
到:
cipher = Cipher.getInstance("AES/CBC/NoPadding");
关于使用 key 和 iv 的 Java AES block 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13419702/