在java中解密错误

我试图encryption/解密Java中的string。 没有关于encryption的问题,然后存储在sqlite表中。 但是我总是得到同样的错误试图解密它:

java.security.InvalidKeyException:当一个预期的没有IV设置”

这是我的代码片段:

public String encrypt(String password){ try { String key = "mysecretpassword"; SecretKeySpec keySpec = null; keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); return new String(cipher.doFinal(password.getBytes())); } catch (Exception e) { return null; } } public String decrypt(String password){ try { String key = "mysecretpassword"; SecretKeySpec keySpec = null; keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE,keySpec); return new String(cipher.doFinal(password.getBytes())); } catch (Exception e) { System.out.println(e); return null; } } 

我究竟做错了什么?

Solutions Collecting From Web of "在java中解密错误"

您将需要在cipher.init()方法中指定一个初始化向量:

 IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); cipher.init(Cipher.DECRYPT_MODE,keySpec, ivSpec); 

请参阅: http : //docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/IvParameterSpec.html

初始化向量应该是一个随机的字节数组,讨论参见:

http://en.wikipedia.org/wiki/Initialization_vector

您需要一个适当的AES密钥,请尝试:

  String key = "mysecretpassword"; KeySpec spec = new PBEKeySpec(key.toCharArray(), Salt, 12345678,256); SecretKey encriptionKey = factory.generateSecret(spec); Key encriptionKey = new SecretKeySpec(encriptionKey.getEncoded(), "AES");