Decryption error in java

I am trying to encrypt / decrypt a String in Java. No encryption problems, then save to sqlite table. But I always get the same error that tries to decrypt it:

"java.security.InvalidKeyException: no IV set if expected"

Here is my code snippet:

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; } } 

What am I doing wrong?

+8
java android sqlite encryption
source share
2 answers

You need to specify the initialization vector in the cipher.init () method:

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

See: http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/IvParameterSpec.html

The initialization vector must be a random byte array, for a discussion see:

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

+10
source share

You need the appropriate AES key, try:

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

All Articles