package HdfcEmandate;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    private static final String ALGO = "AES/ECB/PKCS5Padding";
    private static final String KEY = "k2hLr4X0ozNyZByj5DT66edtCEee1x+6";

    public static String encrypt(String data) {
        try {
            // ✅ Use RAW key (NOT Base64 decode)
            byte[] keyBytes = KEY.getBytes("UTF-8");
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

            Cipher cipher = Cipher.getInstance(ALGO);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));

            return bytesToHex(encryptedBytes);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String hexEncryptedData) {
        try {
            byte[] keyBytes = KEY.getBytes("UTF-8");
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

            Cipher cipher = Cipher.getInstance(ALGO);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            byte[] encryptedBytes = hexToBytes(hexEncryptedData);

            byte[] decrypted = cipher.doFinal(encryptedBytes);

            return new String(decrypted, "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            String s = Integer.toHexString(0xff & b);
            if (s.length() == 1) hex.append('0');
            hex.append(s);
        }
        return hex.toString();
    }

    private static byte[] hexToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) (
                (Character.digit(hex.charAt(i), 16) << 4)
              + Character.digit(hex.charAt(i + 1), 16)
            );
        }
        return data;
    }

    public static void main(String[] args) {
        String enc = AESUtil.encrypt("Naman");
        System.out.println("Encrypted: " + enc);

        String dec = AESUtil.decrypt(enc);
        System.out.println("Decrypted: " + dec);
    }
}