这是我的解码类,它使用Bouncycastle,Rijndael 256解密。我有一个错误:
mode.doFinal(decoded, bytesProcessed);
堆栈跟踪:
org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
at org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(Unknown Source)
at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(Unknown Source)
at com.imocom.cryptography.Decoder.decrypt(Decoder.java:71)
at TestingLauncher.main(TestingLauncher.java:46)
这是执行编码的php代码:
<?php
$string = "This is a sample string.";
$secret = "1234567890987654321234567898765";
$result = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,
$secret,
$string,
MCRYPT_MODE_CBC,
"1234567890123455555555555555555"
));
echo $result."\n";
$back = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,
$secret,
base64_decode($result),
MCRYPT_MODE_CBC,
"12345678999999999999999999999999");
echo $back."\n";
?>
这是电话:
byte[] decoded;
decoded = decoder.decrypt(Base64.decodeBase64(encodedTextFromServer));
任何人都可以帮助我,为什么会这样?
public class Decoder {
byte[] IV = null;
byte[] encryptionKey = null;
Cipher cipher;
SecretKeySpec key;
BlockCipher blockCipher;
ParametersWithIV _param;
PaddedBufferedBlockCipher mode;
int blockSize;
public Decoder() {
Security.addProvider(new BouncyCastleProvider());
try {
IV = "1234543333333333333333333333333".getBytes("UTF-8");
encryptionKey = "12222222222222222222222222222222".getBytes("UTF-8");
blockCipher = new CBCBlockCipher(new RijndaelEngine(256));
_param = new ParametersWithIV(new KeyParameter(encryptionKey), IV);
mode = new PaddedBufferedBlockCipher(blockCipher);
blockSize = blockCipher.getBlockSize();
} catch (Exception e) {
}
}
public byte[] decrypt(byte[] encodedText) {
byte[] decoded = new byte[mode.getOutputSize(encodedText.length)];
try {
mode.init(false, _param);
int bytesProcessed = mode.processBytes(encodedText, 0, encodedText.length, decoded, 0);
mode.doFinal(decoded, bytesProcessed);
} catch (Exception e) {
e.printStackTrace();
}
return decoded;
}
答案 0 :(得分:3)
来自Bouncy Castle中构造函数PaddedBufferedBlockCipher
的JavaDoc:
创建缓冲块密码PKCS7填充
但是PHP默认情况下不使用良好的填充模式,而是简单地添加零值字节,直到到达块的末尾。这在Bouncy Castle中被称为ZeroBytePadding
。
所以请使用ZeroBytePadding
,或者更好,在PHP中实现PKCS#7填充。
答案 1 :(得分:-1)
我建议您尝试将字符串视为十六进制而不是UTF-8。例如,您的IV是“81a577a68f9e94d6cc02fe23b6ee64a4”。这是16字节的十六进制或32字节的UTF-8。 AES IV应为16字节以匹配块大小。我可以看到其他错误,但我会留下那些给你找,因为你说这是为了一个班级。