AES工具类

package com.yinhai.util;



import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

/**
 * AES的加密和解密
 * @ClassName: AesUtil
 * @author 
 * @version V1.0
 */
public class AESUtils {
    private static final String CHARSET = "utf-8";
    public static String AES_IV = "ABC0123456789DEF";
    //算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
    private static final String ALGORITHM = "AES";
    /**
     * 加密
     *
     * @param context
     * @return
     */
    public static String encrypt(String context) throws Exception {
        // 秘钥
        String aesKey = IConst.REQ_AES_KEY;
        byte[] decode = context.getBytes(CHARSET);
        byte[] key = aesKey.getBytes(CHARSET);
        byte[] iv = AES_IV.getBytes(CHARSET);
        byte[] bytes =  cipherFilter(decode, Cipher.ENCRYPT_MODE, key, iv);
        byte[] encodeBase64 = Base64.encodeBase64(bytes);

        return new String(encodeBase64);
    }
    /**
     * 解密
     *
     * @param context
     * @return
     */
    public static String decrypt(String context) throws Exception {
        String aesKey = IConst.REQ_AES_KEY;
        context = context.replaceAll(" ","");
        Base64 base64 = new Base64();
        byte[] decode = base64.decode(context);
        byte[] key = aesKey.getBytes(CHARSET);
        byte[] iv = AES_IV.getBytes(CHARSET);
        byte[] bytes =  cipherFilter(decode, Cipher.DECRYPT_MODE, key, iv);
        return new String(bytes, CHARSET);
    }


    private static byte[] cipherFilter(byte[] context, int opmode, byte[] key, byte[] iv) throws Exception {
        Key secretKeySpec = new SecretKeySpec(key, ALGORITHM);
        AlgorithmParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(opmode, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(context);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值