package com.zcloud.util.hk;
import com.zcloud.util.UuidUtil;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESExample {

    // 固定 AES 密钥
    private static final String FIXED_KEY = "fe58b51278094635800b944e4ae3a871";

    // 将字符串密钥转换为 SecretKey
    private static SecretKey getSecretKey() {
        byte[] keyBytes = hexStringToByteArray(FIXED_KEY);
        return new SecretKeySpec(keyBytes, "AES");
    }

    // 将十六进制字符串转换为字节数组
    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    // 加密方法
    public static String encrypt(String data) throws Exception {
        SecretKey key = getSecretKey();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密方法
    public static String decrypt(String encryptedData) throws Exception {
        SecretKey key = getSecretKey();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }
    // yRL53SBbH1IT10r9Wy9HHg==
    public static void main(String[] args) {
        try {
            String originalData = "z1f9!#q3a7..";

            // 加密
            String encryptedData = encrypt(originalData);
            System.out.println("Encrypted Data: " + encryptedData);

            // 解密
            String decryptedData = decrypt(encryptedData);
            System.out.println("Decrypted Data: " + decryptedData);

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