package com.qmth.jkserver.core;

import com.qmth.jkserver.constant.SystemConstant;

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

public class AesEncryptUtil {

    private static final String AES_KEY = "345lkjasdf9asd0v";

    private static final String SPEC = "0102030405060708";

    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    private static byte[] hex2byte(String strhex) {
        if (strhex == null) {
            return null;
        }
        int l = strhex.length();
        if (l % 2 == 1) {
            return null;
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
        }
        return b;
    }

    public static String encrypt(String source) {
        if (source == null) {
            return null;
        }

        try {
            byte[] raw = AES_KEY.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(SPEC.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(source.getBytes(SystemConstant.CHARSET_NAME));
            return byte2hex(encrypted).toLowerCase();
        } catch (Exception e) {
            return null;
        }
    }

    public static String decrypt(String source) {
        if (source == null) {
            return null;
        }

        try {
            byte[] raw = AES_KEY.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(SPEC.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted = hex2byte(source);
            byte[] original = cipher.doFinal(encrypted);
            return new String(original, SystemConstant.CHARSET_NAME);
        } catch (Exception ex) {
            return null;
        }
    }

}
