【发布时间】:2016-04-20 12:43:31
【问题描述】:
我想实现这段代码,即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 字节,但不起作用
【问题讨论】:
标签: java encryption bytearray aes initialization-vector