AES加密解密

package com.jst.dc.biz.util;

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

/**
 * @author 犀角
 * @date 2019/10/29 10:29
 * @description AES 对称算法加密、解密工具类
 */
public class AESUtils {
    /** 秘钥长度:128,192 or 256 */
    private static final  int KEY_SIZE = 128;

    /** 加密、解密算法名称 */
    private static final String ALGORITHM = "AES";

    /** 随机数生成器(RNG)算法名称 */
    private static final String RNG_ALGORITHM = "SHA1PRNG";

    /**
     * 生成秘钥对象
     */
    private  static SecretKey generateKey(byte[] key) throws Exception {
        // 创建安全随机数生成器
        SecureRandom random = SecureRandom.getInstance(RNG_ALGORITHM);

        // 设置秘钥Key的字节数组作为安全随机数生成器的种子
        random.setSeed(key);

        // 创建AES算法生成器
        KeyGenerator gen = KeyGenerator.getInstance(ALGORITHM);
        // 初始化算法生成器
        gen.init(KEY_SIZE, random);

        // 生成AES秘钥对象,也可以直接创建秘钥对象
        return gen.generateKey();
    }

    /**
     * 数据加密:明文->密文
     */
   public static byte[] encrypt(byte[] plainBytes, byte[] key) throws Exception {
       // 生成秘钥对象
       SecretKey secKey = generateKey(key);

       // 获取AES密码器
       Cipher cipher = Cipher.getInstance(ALGORITHM);
       // 初始化密码器(加密模型)
       cipher.init(Cipher.ENCRYPT_MODE,secKey);

       // 加密数据,返回密文
       byte[] cipherBytes = cipher.doFinal(plainBytes);

       return cipherBytes;
   }

    /**
     * 数据解密:密文->明文
     */
    public static byte[] decrypt(byte[] cipherBytes, byte[] key) throws Exception {
        // 生成秘钥对象
        SecretKey secretKey = generateKey(key);

        // 获取AES密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        // 初始化密码器(解密模型)
        cipher.init(Cipher.DECRYPT_MODE,secretKey);

        // 解密数据,返回明文
        byte[] plainBytes = cipher.doFinal(cipherBytes);
        return plainBytes;


    }


}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值