AES Decryption doesnt decrypt email but decrypts normal text

119 Views Asked by At

I want to encrypt while saving and decrypt after saving 3 fields namely

  1. first_name
  2. last_name
  3. email

from profile collection

Encryption works fine and decryption also works fine for

  1. first_name
  2. last_name

Problem is decryption fails when it tries to decrypt email

Below is the error i get

Error while decrypting: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption

Below is my code snippet

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class EncryptionUtil {

    private static SecretKeySpec secretKey;
    private static byte[] key;
 
    @EventListener(ApplicationReadyEvent.class)
    public static void setKey() 
    {
        MessageDigest sha = null;
        try {
            String myKey = "2234r4r4frvdcdffrfe3455bt5tk6y678kkjnb8wss3e434";
            key = myKey.getBytes("UTF-8");
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16); 
            secretKey = new SecretKeySpec(key, "AES");
        } 
        catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
 
    public static String encrypt(String strToEncrypt) 
    {
        try
        {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        } 
        catch (Exception e) 
        {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }
 
    public static String decrypt(String strToDecrypt) 
    {
        try
        {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        } 
        catch (Exception e) 
        {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }
}


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
import org.springframework.stereotype.Component;

import com.juv.common.util.EncryptionUtil;

@Component
public class MongoDBBeforeConvertCallBack implements BeforeConvertCallback<Profile> {

    private final Class clazz = getClass();

    private final String className = clazz.getSimpleName();

    private final Logger log = LoggerFactory.getLogger(clazz);

    @Autowired
    private EncryptionUtil encryptionUtil;

    @Override
    public Profile onBeforeConvert(Profile profile, String collection) {

        if(profile != null) {

            profile.setFirstName(this.encryptionUtil.encrypt(profile.getFirstName()));
            profile.setLastName(this.encryptionUtil.encrypt(profile.getLastName()));
            profile.setEmail(this.encryptionUtil.encrypt(profile.getEmail()));

        }

        return profile;
    }
}



import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.mapping.event.AfterSaveCallback;
import org.springframework.stereotype.Component;

import com.juv.common.secondary.dao.Profile;
import com.juv.common.util.EncryptionUtil;

@Component
public class MongoDBAfterSaveCallback implements AfterSaveCallback<Profile> {

    private final Class clazz = getClass();

    private final String className = clazz.getSimpleName();

    private final Logger log = LoggerFactory.getLogger(clazz);

    @Autowired
    private EncryptionUtil encryptionUtil;

    @Override
    public Profile onAfterSave(Profile profile, Document document, String collection) {

        if(profile != null) {
            System.out.println("--------first_name----------: "+profile.getFirstName());
            System.out.println("-------decrypt-firstName----------: "+this.encryptionUtil.decrypt(profile.getFirstName()));
            profile.setFirstName(this.encryptionUtil.decrypt(profile.getFirstName()));
            System.out.println("--------last_name----------: "+profile.getLastName());
            System.out.println("-------decrypt-lastName----------: "+this.encryptionUtil.decrypt(profile.getLastName()));
            profile.setLastName(this.encryptionUtil.decrypt(profile.getLastName()));
            System.out.println("--------email----------: "+profile.getEmail());
            System.out.println("-------decrypt-email----------: "+this.encryptionUtil.decrypt(profile.getEmail()));
            profile.setEmail(this.encryptionUtil.decrypt(profile.getEmail()));

        }

        return profile;
    }

    

}


Below is the screenshot of the logs

enter image description here

What should i do to also able to decrypt email with minimal code changes of the one i have posted

0

There are 0 best solutions below