package com.rf.psychological.security;

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

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Hex;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zzf
 * @description:
 * @date 2021/8/4 15:27
 */
public class AesEncryptUtils {


    private static final String KEY = "Sp5biS+gX+#CqAFF";

    private static final String OFFSET = "ud2E8l6wchltwIDA";

    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/CBC/PKCS5Padding";

    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        SecretKeySpec secretKeySpec =  new SecretKeySpec(encryptKey.getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,iv);
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
//        return Base64.encodeBase64String(b);
//        HEX转码
        return Hex.encodeHexString(b);


    }

    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), "AES");
        IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        // 采用base64算法进行转码,避免出现中文乱码
        // byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        //        HEX转码
        byte [] encryptBytes =  Hex.decodeHex(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    public static String encrypt(String content) throws Exception {
        return encrypt(content, KEY);
    }
    public static String decrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr, KEY);
    }


    public static void main(String[] args) throws Exception {
        Map map=new HashMap<String,String>();
        map.put("key","value");
        map.put("中文","汉字");
        String content = JSONObject.toJSONString(map);
        System.out.println("加密前：" + content);

        String encrypt = encrypt(content, KEY);
        System.out.println("加密后：" + encrypt);

        String decrypt = decrypt(encrypt, KEY);
        System.out.println("解密后：" + decrypt);
    }
}
