我对加密几乎是个新手。
我正在尝试解密一个字节数组,当我提供IV时,我会得到一个异常:InvalidAlgorithmParameterException(预期时未设置iv)。
这是我的代码(iv是一个16字节的数组,它不是空的,并且具有加密时使用的值):
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encriptionKey,new IvParameterSpec(iv));
如果我没有指定IV,密码会被初始化好:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encriptionKey);
为了找到答案,我确实找到了JCEStreamCipher的实现(这里),它可能与我使用的版本不对应,但有一些代码让我觉得我没有正确理解它。
这是代码:
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,但这对我来说没有太大意义。
任何帮助都将不胜感激。
非常感谢,理查德。
已解决。
我使用了错误的SecretKey,而不是您可以为AES创建的密钥。
以前我有:
KeySpec spec = new PBEKeySpec(password.toCharArray(), encryptionKeySalt, 12345,256);
SecretKey encriptionKey = factory.generateSecret(spec);
其创建JCEPBEKey。
我失踪了:
Key encriptionKey = new SecretKeySpec(encriptionKey.getEncoded(), "AES");
这为AES创建了一个合适的密钥。