解密错误:“没有预期的 iv 设置"

2022-01-10 00:00:00 cryptography android java

我几乎是加密新手.

我正在尝试解密一个字节数组,当我提供 IV 时,我遇到了一个异常:InvalidAlgorithmParameterException(预期时未设置 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 字节的数组,它不为空,并且具有加密时使用的值):

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 的实现(here) 这可能与我使用的版本不对应,但有一些代码让我觉得我没有正确理解它.

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 创建的密钥.

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);

创建一个 JCEPBEKey.

which creates a JCEPBEKey.

我失踪了:

Key encriptionKey = new SecretKeySpec(encriptionKey.getEncoded(), "AES"); 

为 AES 创建一个适当的密钥.

which creates an appropiate key for AES.

相关文章