AES加密和解密工具类

AES加密和解密工具类

pom

		<!-- lombok 用于Slf4j日志注解-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- commons-codec -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.15</version>
        </dependency>

工具类

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.ztsk.framework.commons.config.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * AES加密和解密工具类
 */
@Slf4j
@Component
public class AESUtil {

    // AES密码器
    private static Cipher dbCipher;

    // AES密码器
    private static Cipher webCipher;

    // 字符串编码
    private static final String KEY_CHARSET = "UTF-8";

    // 算法方式
    private static final String AES = "AES";

    // 算法/模式/填充
    private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding";
    private static final String CIPHER_ALGORITHM_GCM = "AES/GCM/NoPadding";

    // 私钥大小128/192/256(bits)位 即:16/24/32bytes,暂时使用128,如果扩大需要更换java/jre里面的jar包
    private static final Integer PRIVATE_KEY_SIZE_BIT = 128;
    private static final Integer PRIVATE_KEY_SIZE_BYTE = 16;

    /**
     * 加密
     *
     * secretKey密钥:加密的规则 16位
     * @param plainText
     *            明文:要加密的内容
     * @return cipherText
     * 			     密文:加密后的内容,如有异常返回空串:""
     */
    public static String  encrypt(String plainText,String secretKey) {
//        log.info(String.format("加密入参:%s ,加密秘钥:%s",plainText,secretKey));
        if (StringUtils.isBlank(plainText)){
            return plainText;
        }
        if (secretKey.length() != PRIVATE_KEY_SIZE_BYTE) {
            throw new RuntimeException("AESUtil:Invalid AES secretKey length (must be 16 bytes)");
        }

        // 密文字符串
        String cipherText = "";
        try {
            // 加密模式初始化参数
            initParam(secretKey, Cipher.ENCRYPT_MODE,CIPHER_ALGORITHM_GCM);
            // 获取加密内容的字节数组
            byte[] bytePlainText = plainText.getBytes(KEY_CHARSET);
            // 执行加密
            byte[] byteCipherText = dbCipher.doFinal(bytePlainText);
            cipherText = Base64.encodeBase64String(byteCipherText);
        } catch (Exception e) {
            log.error("AESUtil:encrypt fail!:" + e.getMessage());
            throw new BaseException("AESUtil:encrypt fail!", e);
        }
        return cipherText;
    }

    /**
     * 解密
     *
     * secretKey密钥:加密的规则 16位
     * @param cipherText
     *            密文:加密后的内容,即需要解密的内容
     * @return plainText
     * 		  	      明文:解密后的内容即加密前的内容,如有异常返回空串:""
     */
    public static String decrypt(String cipherText,String secretKey) {
        if (StringUtils.isBlank(cipherText)){
            return cipherText;
        }
        if (secretKey.length() != PRIVATE_KEY_SIZE_BYTE) {
            throw new RuntimeException("AESUtil:Invalid AES secretKey length (must be 16 bytes)");
        }
        // 明文字符串
        String plainText = "";
        try {
            initParam(secretKey, Cipher.DECRYPT_MODE,CIPHER_ALGORITHM_GCM);
            // 将加密并编码后的内容解码成字节数组
            byte[] byteCipherText = Base64.decodeBase64(cipherText);
            if (byteCipherText.length == 0){
                return cipherText;
            }
            // 解密
            byte[] bytePlainText = dbCipher.doFinal(byteCipherText);
            plainText = new String(bytePlainText, KEY_CHARSET);
        } catch (Exception e) {
            log.info("AESUtil:decrypt fail!:"+cipherText);
            return cipherText;
        }
        return plainText;
    }

    /**
     * 是否是密文
     */
    public static boolean isCiphertext(String cipherText,String secretKey) {
        if (StringUtils.isBlank(cipherText)){
            return false;
        }
        if (secretKey.length() != PRIVATE_KEY_SIZE_BYTE) {
            throw new RuntimeException("AESUtil:Invalid AES secretKey length (must be 16 bytes)");
        }
        // 明文字符串
        String plainText = "";
        try {
            initParam(secretKey, Cipher.DECRYPT_MODE,CIPHER_ALGORITHM_GCM);
            // 将加密并编码后的内容解码成字节数组
            byte[] byteCipherText = Base64.decodeBase64(cipherText);
            if (byteCipherText.length == 0){
                return false;
            }
            // 解密
            byte[] bytePlainText = dbCipher.doFinal(byteCipherText);
            plainText = new String(bytePlainText, KEY_CHARSET);
        } catch (Exception e) {
            log.info("AESUtil:decrypt fail!:"+cipherText);
            return false;
        }
        return true;
    }

    /**
     * 加密
     *
     * secretKey密钥:加密的规则 16位
     * @param plainText
     *            明文:要加密的内容
     * @return cipherText
     * 			     密文:加密后的内容,如有异常返回空串:""
     */
    public static String encryptCBC(String plainText,String secretKey) {
        if (StringUtils.isBlank(plainText)){
            return plainText;
        }
        if (secretKey.length() != PRIVATE_KEY_SIZE_BYTE) {
            throw new RuntimeException("AESUtil:Invalid AES secretKey length (must be 16 bytes)");
        }
        // 密文字符串
        String cipherText = "";
        try {
            // 加密模式初始化参数
            initParam(secretKey, Cipher.ENCRYPT_MODE,CIPHER_ALGORITHM_CBC);
            // 获取加密内容的字节数组
            byte[] bytePlainText = plainText.getBytes(KEY_CHARSET);
            // 执行加密
            byte[] byteCipherText = webCipher.doFinal(bytePlainText);
            cipherText = Base64.encodeBase64String(byteCipherText);
        } catch (Exception e) {
            throw new RuntimeException("AESUtil:encrypt fail!", e);
        }
        return cipherText;
    }

    /**
     * 解密
     *
     * secretKey密钥:加密的规则 16位
     * @param cipherText
     *            密文:加密后的内容,即需要解密的内容
     * @return plainText
     * 		  	      明文:解密后的内容即加密前的内容,如有异常返回空串:""
     */
    public static String decryptCBC(String cipherText,String secretKey) {
        if (StringUtils.isBlank(cipherText)){
            return cipherText;
        }
        if (secretKey.length() != PRIVATE_KEY_SIZE_BYTE) {
            throw new RuntimeException("AESUtil:Invalid AES secretKey length (must be 16 bytes)");
        }
        // 明文字符串
        String plainText = "";
        try {
            initParam(secretKey, Cipher.DECRYPT_MODE,CIPHER_ALGORITHM_CBC);
            // 将加密并编码后的内容解码成字节数组
            byte[] byteCipherText = Base64.decodeBase64(cipherText);
            if (byteCipherText.length == 0){
                return cipherText;
            }
            // 解密
            byte[] bytePlainText = webCipher.doFinal(byteCipherText);
            plainText = new String(bytePlainText, KEY_CHARSET);
        } catch (Exception e) {
            log.info("AESUtil:decrypt fail!:"+cipherText);
            return cipherText;
        }
        return plainText;
    }

    /**
     * 初始化参数
     * @param secretKey
     * 			 	密钥:加密的规则 16位
     * @param mode
     * 				加密模式:加密or解密
     */
    public static void initParam(String secretKey, int mode,String cipherAlgorithm) {
        try {
            // 防止Linux下生成随机key
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(secretKey.getBytes());
            // 获取key生成器
            KeyGenerator keygen = KeyGenerator.getInstance(AES);
            keygen.init(PRIVATE_KEY_SIZE_BIT, secureRandom);

            // 获得原始对称密钥的字节数组
            byte[] raw = secretKey.getBytes();

            // 根据字节数组生成AES内部密钥
            SecretKeySpec key = new SecretKeySpec(raw, AES);
            // 根据指定算法"AES/CBC/PKCS5Padding"实例化密码器
            if (CIPHER_ALGORITHM_CBC.equals(cipherAlgorithm)){
                webCipher = Cipher.getInstance(cipherAlgorithm);
                IvParameterSpec iv = new IvParameterSpec(secretKey.getBytes());
                webCipher.init(mode, key, iv);
            }else if (CIPHER_ALGORITHM_GCM.equals(cipherAlgorithm)){
                dbCipher = Cipher.getInstance(cipherAlgorithm);
                GCMParameterSpec iv = new GCMParameterSpec(PRIVATE_KEY_SIZE_BIT,secretKey.getBytes());
                dbCipher.init(mode, key, iv);
            }
        } catch (Exception e) {
            throw new RuntimeException("AESUtil:initParam fail!", e);
        }
    }

    public static void main(String[] args) {
        String s1 = AESUtil.encryptCBC("王", "qwertyuiopqwert8");
        String s = AESUtil.decryptCBC(s1, "qwertyuiopqwert8");
        System.out.println(s);
        System.out.println(s1);
    }

 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值