AES加解密工具类

package com.panchan.tsmese.utils;

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

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

import lombok.extern.slf4j.Slf4j;

/**
 * @Description AES加解密
 * @version 1.0
 * @since JDK1.8
 * @author XueXiangDong
 * @Created on 2018年11月20日
 */
@Slf4j
public class AesUtil {

    /**
     * 加密
     * @param sSrc 需要加密的参数
     * @param sKey 秘钥 可以为空 为空则默认秘钥
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc, String sKey) throws Exception {
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        String other = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(encrypted);
        return other;// 此处使用BASE64做转码功能,同时能起到2次加密的作用。
    }

    /**
     * 解密
     * @param <T>
     * @param sSrc 需要解密的参数
     * @param sKey 秘钥 可以为空 为空则默认秘钥
     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(sSrc);// 先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                log.info("解密后的请求报文为{}", originalString);
                return originalString;
            } catch (Exception e) {
                log.error(e.getMessage());
                return null;
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return null;
        }
    }
}
原文地址:https://www.cnblogs.com/huyanlon/p/10641200.html