企业级AES加解密

废话不多说,直接上代码,复制粘贴即可用

package com.xx.xx.utils;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 加密工具类
 *
 * @author yuan
 */
public class CipherUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(CipherUtil.class);

    protected static final String SECRET_KEY = "sdlfjo234L32fv0o9iNG0LL!!*&1%$#@";

    /**
     * 对称加密
     */
    private static Aes aes;

    /**
     * 获取对称加密算法
     *
     * @return 加密算法
     */
    public static Aes aes() {
        if (null == aes) {
            aes = new Aes();
        }
        return aes;
    }


    /**
     * AES加密工具类
     *
     * @author yuan
     */
    public static class Aes {
        private static final String KEY_ALGORITHM = "AES";
        /**
         * 默认的加密算法
         */
        private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

        /**
         * 密码器
         */
        private static Cipher cipher;

        private Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
            if (null == cipher) {
                cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            }
            return cipher;
        }

        /**
         * AES 加密操作
         *
         * @param content 待加密内容
         * @return 返回Base64转码后的加密数据
         */
        public synchronized String encrypt(String content) {
            try {
                // 创建密码器
                Cipher cipher = getCipher();
                byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
                // 初始化为加密模式
                cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(SECRET_KEY));
                // 加密
                byte[] result = cipher.doFinal(byteContent);
                //base64编码
                return byte2Base64(result);
            } catch (Exception ex) {
                LOGGER.error("数据加密失败,content={},stack info={}", content, ExceptionUtils.getFullStackTrace(ex));
                throw new ArithmeticException("数据加密失败");
            }
        }

        /**
         * AES 解密操作
         *
         * @param content 解密内容
         * @return 解密内容
         */
        public synchronized String decrypt(final String content) {
            try {
                //实例化
                Cipher cipher = getCipher();
                //初始化为解密模式
                cipher.init(Cipher.DECRYPT_MODE, getSecretKey(SECRET_KEY));
                //解密
                byte[] result = cipher.doFinal(base642Byte(content));
                return new String(result, StandardCharsets.UTF_8);
            } catch (Exception ex) {
                LOGGER.error("数据解密失败,content={},stack info={}", content, ExceptionUtils.getFullStackTrace(ex));
                throw new ArithmeticException("数据解密失败");
            }
        }

        /**
         * 生成加密秘钥
         *
         * @return 密钥
         */
        public SecretKeySpec getSecretKey(final String key) {
            try {
                //示例化密钥生成器
                KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
                // 指定算法名称,不同的系统上生成的key是相同的。
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
                random.setSeed(key.getBytes(StandardCharsets.UTF_8));
                //AES 要求密钥长度为 128
                kg.init(128, random);
                //生成一个密钥
                SecretKey secretKey = kg.generateKey();
                // 转换为AES专用密钥
                return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
            } catch (NoSuchAlgorithmException ex) {
                LOGGER.error("数据密钥生成失败,stack info=" + ExceptionUtils.getFullStackTrace(ex));
                throw new ArithmeticException("数据密钥生成失败");
            }
        }
    }

    /**
     * 字节数组转Base64编码
     *
     * @param bytes 内容字节码
     * @return base64编码
     */
    public static String byte2Base64(byte[] bytes) {
        return Base64Utils.encodeToUrlSafeString(bytes);
    }

    /**
     * Base64编码转字节数组
     *
     * @param base64Key base64编码
     * @return 字节数组
     * @throws IOException 异常
     */
    public static byte[] base642Byte(String base64Key) throws IOException {
        return Base64Utils.decodeFromUrlSafeString(base64Key);
    }

    public static void main(String[] args) {
        String content = "D:\\attachment\\file.docx";
        System.out.println("原文=" + content);
        String s1 = CipherUtil.aes().encrypt(content);
        System.out.println("加密结果=" + s1);
        System.out.println("解密结果=" + CipherUtil.aes().decrypt(s1));
    }
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员·猿先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值