8

I'm trying to encrypt/decrypt a String in Java. No problem concerning the encryption then stored a in sqlite table. But I always get the same error trying to decrypt it :

"java.security.InvalidKeyException : no IV set when one 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?

sabadow
  • 5,095
  • 3
  • 34
  • 51
MademoiselleLenore
  • 569
  • 1
  • 10
  • 25
  • Having same issue, don't understand, why it works on encrypt and fails on decrypt? unless by not setting a IV in encrypt a random one is generated? – scottyab Sep 25 '14 at 16:30
  • Just to follow up my previous comment. Yes, you need to set a IV similar to how @Udo has shown below. – scottyab Sep 29 '14 at 08:02
  • Possible duplicate of [Decrypting error : "no iv set when one expected"](http://stackoverflow.com/questions/11503157/decrypting-error-no-iv-set-when-one-expected) – rds Nov 05 '15 at 12:43

2 Answers2

10

You will need to specify an 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 should be a random byte array, for a discussion see:

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

Udo Klimaschewski
  • 5,150
  • 1
  • 28
  • 41
1

You need an appropriate AES key, try with:

 String key = "mysecretpassword";
 KeySpec spec = new PBEKeySpec(key.toCharArray(), Salt, 12345678,256);
 SecretKey encriptionKey = factory.generateSecret(spec);
 Key encriptionKey = new SecretKeySpec(encriptionKey.getEncoded(), "AES");
Shine
  • 3,788
  • 1
  • 36
  • 59