package com.yutou.tools.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESTools {
    private static final String key="fJjSoOM7tDIQN0Ne";
    private static final String model="AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param value 原文
     * @return 密文
     */
    public static String encrypt(String value){
        try {
            KeyGenerator generator=KeyGenerator.getInstance("AES");
            generator.init(128);
            Cipher cipher=Cipher.getInstance(model);
            cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(key.getBytes(),"AES"));
            byte[] bytes=cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.getEncoder().encode(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param value 密文
     * @return 原文
     */
    public static String decrypt(String value){
        try {
            KeyGenerator generator=KeyGenerator.getInstance("AES");
            generator.init(128);
            Cipher cipher=Cipher.getInstance(model);
            cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(key.getBytes(),"AES"));
            byte[] encodeBytes=Base64.getDecoder().decode(value);
            byte[] bytes=cipher.doFinal(encodeBytes);
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
