package com.yiqi.web;

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

public class AESUtil {

    // 从MySQL获取的加密字符串
    private static final String AES_KEY = "1234567890ABCDEF";


    public static void main(String[] args) {
        System.out.println(decrypted("5071966C5504DFE03DDF0D10C56881CF900D9FBA887E0CEF1B320F17152B1AD7"));
//        System.out.println(unhex("371323199711267913"));
    }

    public static String decrypted(String hexString) {
        try {
            byte[] keyBytes = AES_KEY.getBytes("UTF-8"); // AES密钥，长度要求128位，16字节
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptedVal = unhex(hexString);
            // 执行解密
            byte[] decryptedBytes = cipher.doFinal(decryptedVal);
            // 将解密后的字节转换为字符串
            String decryptedText = new String(decryptedBytes, "UTF-8");
            System.out.println("解密字符串: " + hexString + " => " + decryptedText);
            return decryptedText;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static byte[] unhex(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() / 2];
        for (int i = 0; i < byteArray.length; i++) {
            int index = i * 2;
            int high = Character.digit(hexString.charAt(index), 16);
            int low = Character.digit(hexString.charAt(index + 1), 16);
            if (high < 0 || low < 0) {
                return null;
            }
            byteArray[i] = (byte) ((high << 4) | low);
        }
        return byteArray;
    } 

}
