package com.cm;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

public class AesUtil {
    /**
     * AES加密
     *
     * @param encodeRule
     * @param content
     * @return
     * @throws Exception
     */
    public static String aesEncoder(String encodeRule, String content) throws Exception {
        // 1.构造秘钥生成器
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        // 2.根据编码规则构建秘钥生成器
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(encodeRule.getBytes());
        keyGenerator.init(128, random);
        // 3.产生堆成秘钥
        SecretKey secretKey = keyGenerator.generateKey();
        // 4.对称秘钥原始数组
        byte[] secretKeyByte = secretKey.getEncoded();
        // 5.生成AES秘钥
        SecretKey key = new SecretKeySpec(secretKeyByte, "AES");
        // 6.初始化密码器
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        // 8.获取加密内容字节数组
        byte[] contentByte = content.getBytes("UTF-8");
        // 9.加密
        return new String(Base64.encodeBase64(cipher.doFinal(contentByte)));
    }

    /**
     * AES解密
     *
     * @param encodeRule
     * @param content
     * @return
     * @throws Exception
     */
    public static String aesDecoder(String encodeRule, String content) throws Exception {
        // 1.构建秘钥生成器
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        // 2.根据编码规则构建秘钥生成器
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(encodeRule.getBytes());
        keyGenerator.init(128, random);
        // 3.生成对称解密秘钥
        SecretKey secretKey = keyGenerator.generateKey();
        // 4.对称秘钥原始数组
        byte[] secretKeyByte = secretKey.getEncoded();
        // 5.生成AES秘钥
        SecretKey key = new SecretKeySpec(secretKeyByte, "AES");
        // 6.初始化密码器
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        // 7.要解密内容的字节数组
        byte[] contentByte = Base64.decodeBase64(content);
        // 8.解密
        return new String(cipher.doFinal(contentByte), "UTF-8");
    }
}
