使用密钥和iv进行Java AES块解密

时间:2012-11-16 15:36:53

标签: java security aes

我正在尝试将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:输入数据

1 个答案:

答案 0 :(得分:1)

通常BadPaddingException表示:

  • 使用您建议的填充算法填充原始明文。因此,数据加密时可能没有使用PKCS#5。

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

希望您可以查看您的环境并找出其中任何一个是否可能?看看你的BouncyCastle代码,我假设你根本没有使用填充。尝试更改:

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

为:

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