如何使用 BouncyCastle API 为 Rijndael-256 做些什么?
How can I do for Rijndael-256 with BouncyCastle API?
一位古老的 PHP 人为 Rijndael-256 (!AES256) / ECB / NoPadding
编写了加密代码。
我试过了。
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new RijndaelEngine(256), new ZeroBytePadding());
cipher.init(encrypt, new KeyParameter(Arrays.copyOf(KEY.getBytes(UTF_8), 16)));
byte[] source = supplier.get();
byte[] target = new byte[cipher.getOutputSize(source.length)];
int offset = cipher.processBytes(source, 0, source.length, target, 0);
cipher.doFinal(target, offset);
但加密总是会添加填充。是的,我知道我用过 ZeroBytePadding
.
我该如何解决这个问题?我没有找到任何好的参考资料。
如果加密真的没有加填充,那么只需将密码初始化为:
new BufferedBlockCipher(new RijndaelEngine(256))
请注意,如果您尝试解密的数据实际上不是块对齐的,doFinal
调用将抛出 DataLengthException
。
顺便说一句,检查 doFinal
的 return 值(输出了多少字节)也是一个好习惯,因为 getOutputSize
允许被高估。
我正在根据已接受的答案分享我的(可能的)解决方案。
BufferedBlockCipher cipher =
new BufferedBlockCipher(new RijndaelEngine(256));
cipher.init(encrypt, new KeyParameter(Arrays.copyOf(KEY.getBytes(UTF_8), 16)));
byte[] source = supplier.get();
byte[] target = new byte[cipher.getOutputSize(source.length)];
int offset = cipher.processBytes(source, 0, source.length, target, 0);
try {
offset += cipher.doFinal(target, offset);
} catch (InvalidCipherTextException icte) {
// if padding is expected and not found
//throw new RuntimeException(icte);
}
target = Arrays.copyOf(target, offset);
不过我不确定。
一位古老的 PHP 人为 Rijndael-256 (!AES256) / ECB / NoPadding
编写了加密代码。
我试过了。
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new RijndaelEngine(256), new ZeroBytePadding());
cipher.init(encrypt, new KeyParameter(Arrays.copyOf(KEY.getBytes(UTF_8), 16)));
byte[] source = supplier.get();
byte[] target = new byte[cipher.getOutputSize(source.length)];
int offset = cipher.processBytes(source, 0, source.length, target, 0);
cipher.doFinal(target, offset);
但加密总是会添加填充。是的,我知道我用过 ZeroBytePadding
.
我该如何解决这个问题?我没有找到任何好的参考资料。
如果加密真的没有加填充,那么只需将密码初始化为:
new BufferedBlockCipher(new RijndaelEngine(256))
请注意,如果您尝试解密的数据实际上不是块对齐的,doFinal
调用将抛出 DataLengthException
。
顺便说一句,检查 doFinal
的 return 值(输出了多少字节)也是一个好习惯,因为 getOutputSize
允许被高估。
我正在根据已接受的答案分享我的(可能的)解决方案。
BufferedBlockCipher cipher =
new BufferedBlockCipher(new RijndaelEngine(256));
cipher.init(encrypt, new KeyParameter(Arrays.copyOf(KEY.getBytes(UTF_8), 16)));
byte[] source = supplier.get();
byte[] target = new byte[cipher.getOutputSize(source.length)];
int offset = cipher.processBytes(source, 0, source.length, target, 0);
try {
offset += cipher.doFinal(target, offset);
} catch (InvalidCipherTextException icte) {
// if padding is expected and not found
//throw new RuntimeException(icte);
}
target = Arrays.copyOf(target, offset);
不过我不确定。