問題描述
我?guī)缀跏羌用苄率?
我正在嘗試解密一個字節(jié)數(shù)組,當(dāng)我提供 IV 時,我遇到了一個異常:InvalidAlgorithmParameterException(預(yù)期時未設(shè)置 iv).
I am trying to decrypt an array of bytes, and when I am providing the IV I am getting an exception : InvalidAlgorithmParameterException (no iv set when one expected).
這是我的代碼(iv 是一個 16 字節(jié)的數(shù)組,它不為空,并且具有加密時使用的值):
Here's my code (iv is an array of 16 bytes which is not null and has the values used when encrypting) :
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encriptionKey,new IvParameterSpec(iv));
如果我沒有指定 IV,密碼會被初始化:
If I don't specify the IV the cipher gets initialized ok :
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encriptionKey);
試圖找到答案,我確實找到了 JCEStreamCipher 的實現(xiàn)(here) 這可能與我使用的版本不對應(yīng),但有一些代碼讓我覺得我沒有正確理解它.
Trying to find an answer I did find an implementation of JCEStreamCipher (here) which may not correspond to the version I am using but has some code that makes me thing I am not understanding it correctly.
代碼如下:
if ((ivLength != 0) && !(param instanceof ParametersWithIV))
{
SecureRandom ivRandom = random;
if (ivRandom == null)
{
ivRandom = new SecureRandom();
}
if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE))
{
byte[] iv = new byte[ivLength];
ivRandom.nextBytes(iv);
param = new ParametersWithIV(param, iv);
ivParam = (ParametersWithIV)param;
}
else
{
throw new InvalidAlgorithmParameterException("no IV set when one expected");
}
}
看起來我在解密時無法提供 IV,但這對我來說沒有太大意義.
Looks like I cannot provide an IV when decrypting, but it doesn't makes too much sense to me.
任何幫助將不勝感激.
非常感謝,理查德.
推薦答案
已解決.
我使用了錯誤的 SecretKey,而不是您可以為 AES 創(chuàng)建的密鑰.
I was using a wrong SecretKey, not the one you can create for AES.
以前我有:
KeySpec spec = new PBEKeySpec(password.toCharArray(), encryptionKeySalt, 12345,256);
SecretKey encriptionKey = factory.generateSecret(spec);
創(chuàng)建一個 JCEPBEKey.
which creates a JCEPBEKey.
我失蹤了:
Key encriptionKey = new SecretKeySpec(encriptionKey.getEncoded(), "AES");
為 AES 創(chuàng)建一個適當(dāng)?shù)拿荑€.
which creates an appropiate key for AES.
這篇關(guān)于解密錯誤:“沒有預(yù)期的 iv 設(shè)置"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!