我想实现这个代码,即CBC模式下的AES加密和内联IV,但是有这样的错误消息:
错误的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字节,但不起作用
答案 0 :(得分: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初始化为全零,这符合你的最佳利益。见how to pick an IV