Search code examples
javaencryptionaesjava-security

AES deterministic encryption


I want to implement a deterministic encryption and I'm trying to figure out why the decryption doesn't work in the code below. Decrypted text is different from the original??

    public static String encryptID(String id) {

    String encryptedID = "";

    try {
        SecretKeySpec secretKey = new SecretKeySpec(Constants.ID_KEY.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));

        encryptedID = new BASE64Encoder().encodeBuffer(cipher.doFinal(id.getBytes("UTF-8")));
    } catch (Exception e) {
        log.error("Encryption error. Unable to encrypt ID.", e);
        encryptedID = "ERROR";
    }

    return encryptedID;
}

public static String decryptID(String encryptedID) {

    String decryptedID = "";

    try {
        SecretKeySpec secretKey = new SecretKeySpec(Constants.ID_KEY.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));

        byte[] decodedValue = cipher.doFinal(new BASE64Decoder().decodeBuffer(encryptedID));
        decryptedID = new String(decodedValue);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return decryptedID;

}

Test code:

    @Test
    public void testEncryption() {

    String ecryptedID = DataUtil.encryptID("123456789");
    System.out.println(ecryptedID);
    System.out.println(DataUtil.decryptID(ecryptedID)); 

}

Output:
KB8P+heBaNSaibJoJSImLQ==
—#@†zXÝ£ˆþhµORCôìÊ ˆf/…ºÁ´®


Solution

  • You're encrypting the string again instead of decrypting it

    public static String decryptID(String encryptedID) {
    ...
                       |||||||
                       vvvvvvv
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));