package HdfcEmandate;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AES256Util {

    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    // 🔑 Base64 → AES-192 key (24 bytes)
    private static SecretKeySpec getKey(String base64Key) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64Key);

        if (keyBytes.length != 24) {
            throw new IllegalArgumentException("Key must be 24 bytes for AES-192");
        }

        return new SecretKeySpec(keyBytes, "AES");
    }

    // 🔁 Convert bytes → HEX
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();
    }

    // 🔐 Encrypt (same as tool)
    public static String encrypt(String plainText, String base64Key) throws Exception {

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, getKey(base64Key));

        // 🔥 UTF-8 (same as tool)
        byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));

        return bytesToHex(encrypted);
    }

    public static void main(String[] args) {
        try {
            String key = "k2hLr4X00zNyZByjSDT66edtCEeelx+6";
            String input = "Naman";

            String encrypted = encrypt(input, key);

            System.out.println("Input     : " + input);
            System.out.println("Encrypted : " + encrypted);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}