我是靠谱客的博主 健壮西装,最近开发中收集的这篇文章主要介绍AES加密解密工具类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

        最近项目使用到了aes的加解密算法,但是在使用过程中出现了诸多问题,比如bc库版本冲突、并发下bc对象占用解密失败,重复new bc库导致加解密速度太慢等。。。最后经过一番分析,现在分享一下彻底解决这些问题的版本;

1、依赖版本(最好使用这个,支持jdk1.5及以上,算是比较新的)

<dependency>
       <groupId>org.bouncycastle</groupId>
       <artifactId>bcprov-jdk15on</artifactId>
       <version>1.56</version>
</dependency>

2、重头戏,加解密工具类;

package util;

import com.edi.framework.core.utils.StringUtils;
import com.edi.framework.core.utils.encrypt.Base64Util;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;
public class AESUtil {

    private AESUtil() {
    }

    private static AESUtil instance;

    public static AESUtil getInstance() {
        if (instance == null) {
            // 初始化(注意一定全局只初始化一次bc库,很消耗性能,并且多加载无用)
            Security.addProvider(new BouncyCastleProvider());
            instance = new AESUtil();
        }
        return instance;
    }

    /**
     * 加解密秘钥,实际项目中密钥最好使用非对称加密算法动态生成,此处为直接写死
     */
    private final static String ENCRYPT_KEY = "1234567890123456";

    //算法模式
    final String KEY_ALGORITHM = "AES";
    // 加解密算法/模式/填充方式
    final String algorithmStr = "AES/CBC/PKCS7Padding";
    //默认编码格式
    final static String DEFAULT_ENCODING = "UTF-8";
    //加密偏移向量
    byte[] iv = {0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35, 0x30, 0x36, 0x30, 0x37, 0x30, 0x38};

    /**
     * 加密方法(核心方法)
     *
     * @param content  要加密的字符串
     * @param keyBytes 加密密钥
     * @return
     */
    public byte[] encrypt(byte[] content, byte[] keyBytes) throws UnsupportedEncodingException {
        byte[] encryptedText = null;
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        try {
            //以下对象每次使用直接创建即可,不需要提取到公共加载
            Key encryptKey = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
            Cipher encryptCipher = Cipher.getInstance(algorithmStr, "BC");
            encryptCipher.init(Cipher.ENCRYPT_MODE, encryptKey, new IvParameterSpec(iv));
            encryptedText = encryptCipher.doFinal(content);
        } catch (Exception e) {
            throw new UnsupportedEncodingException(e.getMessage());
        }
        return encryptedText;
    }

    /**
     * 解密方法
     *
     * @param encryptedData 要解密的字符串
     * @param keyBytes      解密密钥
     * @return
     */
    public byte[] decrypt(byte[] encryptedData, byte[] keyBytes) throws UnsupportedEncodingException {
        byte[] encryptedText = null;
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        try {
            //以下对象每次使用直接创建即可,不需要提取到公共加载
            Key decryptKey = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
            Cipher decryptCipher = Cipher.getInstance(algorithmStr, "BC");
            decryptCipher.init(Cipher.DECRYPT_MODE, decryptKey, new IvParameterSpec(iv));
            encryptedText = decryptCipher.doFinal(encryptedData);
        } catch (Exception e) {
            throw new UnsupportedEncodingException(e.getMessage());
        }
        return encryptedText;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            String msg = AESUtil.getInstance().encrypt("134");
            System.out.println(msg);
            String result = AESUtil.getInstance().decrypt(msg);
            System.out.println(result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * <p>方法名称: encrypt | 描述: 加密字符串</p>
     *
     * @param source
     * @return java.lang.String
     * @author: gdq
     * @date: 2019/7/12 9:37 AM
     */
    public String encrypt(String source) throws UnsupportedEncodingException {
        byte[] encryptSource = AESUtil.getInstance().encrypt(source.getBytes(DEFAULT_ENCODING), ENCRYPT_KEY.getBytes(DEFAULT_ENCODING));
        String sourceDecreypt = Base64Util.encodeBase64String(encryptSource);
        sourceDecreypt = sourceDecreypt.replaceAll("rn", "");
        sourceDecreypt = sourceDecreypt.replaceAll("n", "");
        return sourceDecreypt;
    }

    /**
     * <p>方法名称: decrypt | 描述: 解密字符串</p>
     *
     * @param source
     * @return java.lang.String
     * @author: gdq
     * @date: 2019/7/16 1:30 PM
     */
    public String decrypt(String source) throws UnsupportedEncodingException {
        source = source.replaceAll("rn", "");
        source = source.replaceAll("n", "");
        byte[] encryptSource = Base64Util.decodeBase64byte(source);
        String sourceDecreypt = new String(AESUtil.getInstance().decrypt(encryptSource, ENCRYPT_KEY.getBytes(DEFAULT_ENCODING)), DEFAULT_ENCODING);
        return sourceDecreypt;
    }
}

如有不同看法,欢迎各位提出指正,共同进步

最后

以上就是健壮西装为你收集整理的AES加密解密工具类的全部内容,希望文章能够帮你解决AES加密解密工具类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部