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);
}
}
AES工具类
最新推荐文章于 2023-02-02 11:00:16 发布