Amir M
Amir M

Reputation: 354

Decryption of AES encrypted field in java

I tried to encrypt a field with java, but i cannot decrypt it back.

I'm not sending data, I just want it to be encrypted upon insertion and decrypted when retrieving.

I used this code but decryption doesn't work.

public void setkey() throws Exception {
    byte[] key1 = new String("abcd").getBytes("UTF-8"); // some logic will replace "abcd"
     MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
     key1 = messageDigest.digest(key1);
     key1 = Arrays.copyOf(key1,16);
     key = key1;
     //this key must be the same when encrypting and decrypting, right?
}

@Override
public String encryptField(Myclass myClass) throws Exception {

    Cipher cipher = Cipher.getInstance("AES");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    String encryptedField = Base64.encodeBase64String(cipher.doFinal(myClass.myField.getBytes("UTF-8")));
    myClass.setMyField(encryptedField);
    save(myClass);

    return encryptedField;
    //this looks OK, and gives me 24 character string.
}


@Override
public String decryptVoucher(Myclass myClass) throws Exception {

    String skey = key.toString();
    Cipher cipher = Cipher.getInstance("AES");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] decryptedField = cipher.doFinal(Base64.decodeBase64(yClass.myField.getBytes("UTF-8")));
    // decryptedField.toString() is not as same as original data...
    return decryptedField.toString();
}

ps : I already searched and read this and this, in fact I'm here with their help.

Upvotes: 0

Views: 501

Answers (1)

Cameron Skinner
Cameron Skinner

Reputation: 54276

The problem is that you are calling the toString method on a byte array. toString gives you a String representation of the array object; it does not attempt to convert the contents of the array into a String. The output you're seeing is something along the lines of "[B@798b429b", right?

To convert your decrypted bytes into a String object use new String(decryptedField, "UTF-8"). That will correctly convert the bytes into characters.

Remember that Java has no way of knowing that the byte array contains data that represents characters. The toString method on the Array class returns a description of the array, not its contents. It uses the default toString implementation, which is:

getClass().getName() + '@' + Integer.toHexString(hashCode())

(from http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29)

In this case, the class name is "[B" meaning "array of bytes".

Upvotes: 1

Related Questions