AesEncryptUtils.java 2.88 KB
package cn.com.glsx.smart.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

/**
 * @author fengzhi
 * @version V1.0
 * @Description: AES加密工具类
 */
@Component
public class AesEncryptUtils {
    /**
     * crep的解密key
     * 可配置到Constant中,并读取配置文件注入,16位
     */
    @Value("${aesencrypt.key}")
    private String KEY;
    /**
     * 参数分别代表
     * 算法名称/加密模式/数据填充方式
     */
    @Value("${aesencrypt.algorithmstr}")
    private String ALGORITHMSTR;

    /**
     * secretKey的解密key
     */
    @Value("${aesencrypt.secret.key}")
    private String SECRET_KEY;

    /**
     * 加密
     *
     * @param content    加密的字符串
     * @param encryptKey 加密的key值
     */
    public String encrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);

    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     */
    public String decrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    /**
     * 加密crep
     * @param content 明文
     */
    public String encrypt(String content) throws Exception {
        return encrypt(content, KEY);
    }

    /**
     * 解密crep
     * @param encryptStr 密文
     */
    public String decrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr, KEY);
    }

    /**
     * 加密secretKey
     * @param content 明文
     */
    public String encryptSecret(String content) throws Exception {
        return encrypt(content, SECRET_KEY);
    }

    /**
     * 解密secretKey
     * @param encryptStr 密文
     */
    public String decryptSecret(String encryptStr) throws Exception {
        return decrypt(encryptStr, SECRET_KEY);
    }
}