Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error decrypting in java

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?

like image 336
MademoiselleLenore Avatar asked Nov 06 '12 15:11

MademoiselleLenore


People also ask

What is decryption error?

The message means that entered password does not correspond to a fingerprint stored in application storage. There might be two reasons for these issue: 1. Application has been reinstalled with a password, other then one used with previous installation to encrypt database.

What is mean by decrypting?

What is Decryption. Definition: The conversion of encrypted data into its original form is called Decryption. It is generally a reverse process of encryption. It decodes the encrypted information so that an authorized user can only decrypt the data because decryption requires a secret key or password.

What is an example of decryption?

Suppose it is established that 2 x = y; then the key for the function has been established, and all possible values of x and y can be mapped. In a simplified form, this is what occurs in decryption. The example shown is one that could easily be solved by what are called “bruteforce” means.


1 Answers

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

like image 96
Udo Klimaschewski Avatar answered Sep 20 '22 11:09

Udo Klimaschewski