【问题标题】:How can I do for Rijndael-256 with BouncyCastle API?如何使用 BouncyCastle API 为 Rijndael-256 做些什么?
【发布时间】:2018-05-24 19:51:49
【问题描述】:

一个古老的 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

我该如何解决这个问题?我没有找到任何好的参考资料。

【问题讨论】:

  • 明文长度必须是块大小的倍数,在本例中为 32 字节。填充方案确保发生这种情况。

标签: java bouncycastle rijndael


【解决方案1】:

如果加密确实没有添加填充,那么只需将密码初始化为:

new BufferedBlockCipher(new RijndaelEngine(256))

请注意,如果您尝试解密的数据实际上不是块对齐的,doFinal 调用将引发 DataLengthException

顺便说一句,检查doFinal 的返回值(输出了多少字节)也是一个好习惯,因为getOutputSize 允许高估。

【讨论】:

  • 我不确定,但我发现我应该关心的是InvalidCipherTextException
【解决方案2】:

我正在根据接受的答案分享我的(可能的)解决方案。

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);

不过我不确定。

【讨论】:

  • 此代码仍在创建“new PaddedBufferedBlockCipher(...)”,但它应该创建“new BufferedBlockCipher(...)”,如我的回答中所述。
猜你喜欢
  • 1970-01-01
  • 2011-12-26
  • 2013-07-07
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 2012-01-25
相关资源
最近更新 更多