AES加密解密工具类

使用AES加解密,加密时里面包含偏移量

package com.citicsc.finance.agent.util;

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

import org.springframework.util.Base64Utils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AESUtil {
	
	private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";//默认的加密算法
    private static int offset = 16;

    public static void main(String[] args) {
		System.out.println(AESUtil.encrypt("147258", "cmx.algo.PF.2014", "ItAqS_lIqUiD_pRo"));
		System.out.println(AESUtil.decrypt("WuQ8bQB0GjNbMbjXWPRibw==", "cmx.algo.PF.2014", "ItAqS_lIqUiD_pRo"));
	}

    public static String encrypt(String content, String secretKey, String ivKey) {
        try {
            //构造密钥
            SecretKeySpec skey = new SecretKeySpec(secretKey.getBytes(), KEY_ALGORITHM);
            //创建初始向量iv用于指定密钥偏移量(可自行指定但必须为128位),因为AES是分组加密,下一组的iv就用上一组加密的密文来充当
            IvParameterSpec iv = new IvParameterSpec(ivKey.getBytes(), 0, offset);
            //创建AES加密器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            byte[] byteContent = content.getBytes();
            //使用加密器的加密模式
            cipher.init(Cipher.ENCRYPT_MODE, skey, iv);
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            //使用BASE64对加密后的二进制数组进行编码
            return Base64Utils.encodeToString(result);
        } catch (Exception ex) {
        	log.error("encrypt", ex);
        	throw new RuntimeException(ex);
        }
    }
    
    
    /**
     * AES 解密操作
     *
     * @param content
     * @param password
     * @return
     */
    public static String decrypt(String content, String secretKey, String ivKey) {
        try {
        	SecretKeySpec skey = new SecretKeySpec(secretKey.getBytes(), KEY_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(ivKey.getBytes(), 0, offset);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //解密时使用加密器的解密模式
            cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化
            byte[] result = cipher.doFinal(Base64Utils.decode(content.getBytes()));
            return new String(result); // 解密
        } catch (Exception ex) {
        	log.error("decrypt", ex);
        	throw new RuntimeException(ex);
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值