package com.evobms.common.utils;

import org.apache.tomcat.util.buf.Ascii;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES/ECB/PKCS5Padding 加密工具（输出Base64字符串）
 */
public final class AesEcbPkcs5Utils {

    private AesEcbPkcs5Utils() {}

    /**
     * 使用 AES/ECB/PKCS5Padding 进行加密，返回16进制ASCII字符串
     * @param plaintext 明文
     * @param key16 长度16的密钥（UTF-8）
     */
    public static String encryptToAscII16(String plaintext, String key16) throws Exception {
        if (key16 == null) {
            throw new IllegalArgumentException("AES key must not be null");
        }
        byte[] keyBytes = key16.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(encrypted);
    }

    /**
     * 将字节数组转换为大写16进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}
