package io.hmit.common.validator;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

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

@Slf4j
public class AESUtils {

    private static final String ALGORITHM = "AES";
    private static final String CHARSET_NAME = "UTF-8";
    private static final String DEF_KEY = "2020020202020202";

    public static String decrypt(String content) {
        return decrypt(content, DEF_KEY);
    }

    public static String decrypt(String content, String key) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(CHARSET_NAME), ALGORITHM);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // "算法/模式/补码方式"
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            return new String(cipher.doFinal(Base64.decodeBase64(content)));
        } catch (Exception e) {
            log.error("AES decrypt error", e);
        }
        return null;
    }

    public static String encrypt(String content) {
        return encrypt(content, DEF_KEY);
    }

    public static String encrypt(String content, String key) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(CHARSET_NAME), ALGORITHM);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);//ENCRYPT_MODE指加密操作
            return Base64.encodeBase64String(cipher.doFinal(content.getBytes(CHARSET_NAME)));

        } catch (Exception e) {
            log.error("AES encrypt error, [key = " + key + "]", e);
        }
        return null;
    }

    public static void main(String[] args) {
        String key = "20210106153411242021010615341124";
        String encrypt = encrypt("1124", key);

        String decrypt = decrypt(encrypt, key);
        System.out.println(encrypt);
        System.out.println(decrypt);
    }
}
