簡體   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