package com.ms.biz.tool.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * AES加解密
 *
 * https://www.jianshu.com/p/13b7fd018f7c
 */
public class AES {
    private String key;

    public AES(String key)
    {
        this.key = key;
    }

    /**
     * 加密
     *
     * @param context
     * @return
     * @throws Exception
     */
    public byte[] encode(String context) throws Exception
    {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
        return cipher.doFinal(context.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 解密
     *
     * @param encryptBytes
     * @return
     * @throws Exception
     */
    public String decode(byte[] encryptBytes) throws Exception
    {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes, "UTF-8");
    }
}