繁体   English   中英

使用密钥和iv的Java AES块解密

[英]Java AES block decryption using key and iv

我正在尝试将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。

  • 您使用了错误的密钥进行解密。 当解密完成时,这导致填充看起来不正确。

希望您可以查看您的环境并弄清楚是否有可能? 查看您的BouncyCastle代码,我假设您根本没有使用填充。 尝试更改:

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

至:

cipher = Cipher.getInstance("AES/CBC/NoPadding");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM