2014-12-08 118 views
2

以下是我的加密逻辑。虽然我的IV是16字节长,但我仍然遇到IV无效的错误。希望得到任何帮助AES 256位加密 - java.security.InvalidAlgorithmParameterException:错误IV长度:必须为16字节长

@Override 
public String encrypt(String dataToEncrypt, String IV) throws Exception{ 
    if(encryptionKey.length() < 10){ 
     encryptionKey = generateEncryptionKey().toString(); 
    } 
    System.out.println("number of IV bytes is "+IV.length()+" "+IV); 
    Cipher cipher = Cipher.getInstance(encrpytionAlgo); 
    SecretKey key = new SecretKeySpec(encryptionKey.getBytes(Charset.forName("UTF-8")), "AES"); 
    cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes(Charset.forName("UTF-8")))); 
    byte[] encryptedTextBytes = cipher.doFinal(dataToEncrypt.getBytes(Charset.forName("UTF-8"))); 
    return new Base64().encodeAsString(encryptedTextBytes); 
} 

IV和密钥生成逻辑

@Override 
public String generateRandomIV(){ 
     Random random = new SecureRandom(); 
     byte[] iv = new byte[16]; 
     random.nextBytes(iv); 
     System.out.println("IV is "+Base64.encodeBase64(iv)+" "+ com.sun.jersey.core.util.Base64.base64Decode(new String(Base64.encodeBase64(iv)))+ " number of bytes is "+iv.length); 
     return new String(Base64.encodeBase64(iv)); 
} 

@Override 
public SecretKey generateEncryptionKey(){ 
    KeyGenerator aesKey = null; 
    try { 
     aesKey = KeyGenerator.getInstance("AES"); 
    } catch (NoSuchAlgorithmException e) { 
      e.printStackTrace(); 
    } 
    aesKey.init(256); 
    SecretKey secretKey = aesKey.generateKey(); 
    System.out.println("Encryption key is "+ new Base64().encode(secretKey.getEncoded())); 
    return secretKey; 
} 

下面是例外 异常堆栈跟踪是行:
cipher.init(Cipher.ENCRYPT_MODE,钥匙,新IvParameterSpec (IV.getBytes(Charset.forName( “UTF-8”))));

java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long 
at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..) 
at com.sun.crypto.provider.AESCipher.engineInit(DashoA13*..) 
at javax.crypto.Cipher.a(DashoA13*..) 
at javax.crypto.Cipher.a(DashoA13*..) 
at javax.crypto.Cipher.init(DashoA13*..) 
at javax.crypto.Cipher.init(DashoA13*..) 
at com.intuit.platform.publiccloudaccess.core.services.EncryptionServiceImpl.encrypt(EncryptionServiceImpl.java:47) 
+0

我建议你保持你的IV作为一个字节[]。通常,将UTF-8字符串转换为字节数组并不会为每个字符提供一个字节。为什么你想要转换到/从一个字符串的开销呢? – Rob 2014-12-08 04:57:33

+0

感谢@Rob工作。 – outtoexplore 2014-12-18 18:24:04

回答

3

您将您的IV编码为Base64,然后从generateRandomIV返回。在使用它进行加密和解密之前,您必须将其解码。

cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(java.util.Base64.Decoder.decode(IV.getBytes("UTF-8")))); 

Java 8提供了java.util.Base64类,用于获取不同的Base 64编码器和解码器。

1

继罗布的评论,

System.out.println("number of IV bytes is "+IV.length()+" "+IV); 

在这里,你得到IV的长度字符串的条款。然而

cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes(Charset.forName("UTF-8"))));  

这里您提供的IV为字节阵列和制作在字符串的千卡的IV为16的长度并不能保证它的字节表示也是16个字节。所以Rob建议你最好将IV保存在字节数组中,并将其用作字节数组。

相关问题