0

我想实现这段代码,即在 CBC 模式下使用内联 IV 进行 AES 加密,但是有这个错误消息:

IV 长度错误:必须为 16 字节长

代码是:

package implementaes;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec; 
import javax.crypto.spec.SecretKeySpec;

public class Aesaesaes
{
    public static void main(String[] args)
    {
        try
        {
                //Lookup a key generator for the AES cipher
                        KeyGenerator kg = KeyGenerator.getInstance("AES");
            SecretKey key = kg.generateKey();

            SecretKeySpec keySpec = new
                        SecretKeySpec(key.getEncoded(), "AES");     
                //Lookup an instance of a AES cipher
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

                //initialize IV  manually

                byte[] ivBytes = new byte[] {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};

                //create IvParameterSpecobject

                IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);     

               //Initialize the cipher using the secter key

            cipher.init(Cipher.ENCRYPT_MODE, keySpec,ivSpec);

                String plainText = "This is a secret!";



            byte[] cipherText = cipher.doFinal(plainText.getBytes());

            System.out.println("Resulting Cipher Text:\n");
            for(int i=0;i<cipherText.length;i++)
            {
                System.out.print(cipherText[i] + " ");
            }
            System.out.println("");



        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

我该如何解决?顺便说一句,我试过:

byte[] ivBytes = new byte[] {0x00,0x00,0x00,0x00};

为 16 字节,但不起作用

4

1 回答 1

0

您定义的 ivBytes 当前为 8 个字节:

byte[] ivBytes = new byte[] {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};

数组中的每个成员ivBytes代表一个字节。您需要一个包含 16 个条目的数组:

byte[] ivBytes = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};  

更新 我认为很明显您将向 IV 提供您自己的值,但可能值得指出 Dave 的评论,即不将 IV 初始化为全零符合您的最佳利益。了解如何选择 IV

于 2016-04-20T13:08:01.617 回答