package com.xunhong.erp.turbo.datasource.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES加解密
 *
 * @author Hollis
 */
public class AesUtil {

	private static String key = "Rmms3apU4mOsnnEFRUG6aNhcaXNEPpImi0BJb2YPNvg=";
	private static AES aes = SecureUtil.aes(Base64.getDecoder().decode(key));

	public static String encrypt(String content) {
		//判空修改
		if (StringUtils.isBlank(content)) {
			return content;
		}

		return aes.encryptHex(content);
	}

	public static String decrypt(String content) {
		//判空修改
		if (StringUtils.isBlank(content)) {
			return content;
		}

		try {
			return aes.decryptStr(content);
		} catch (Exception e) {
			return content;
		}
	}

	private static void generate() throws Exception {
		// 生成AES密钥
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		// 使用256位AES密钥
		keyGenerator.init(256);
		SecretKey secretKey = keyGenerator.generateKey();
		byte[] keyBytes = secretKey.getEncoded();
		String base64KeyString = Base64.getEncoder().encodeToString(keyBytes);
		// 输出 Base64 编码的字符串
		System.out.println(base64KeyString);
		// 生成随机IV
		// GCM推荐的IV长度是12字节
		byte[] ivs = new byte[12];
		new SecureRandom().nextBytes(ivs);
		String base64IvString = Base64.getEncoder().encodeToString(ivs);
		// 输出 Base64 编码的字符串
		System.out.println(base64IvString);
	}

	public static void main(String[] args) throws Exception {
		generate();
	}
}
