package com.hcp.utils.config;
import org.apache.commons.codec.digest.DigestUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
/**
* AES 加密工具类
*/
public class AesUtil {
// 加密算法RSA
public static final String KEY_ALGORITHM = "AES";
//编码方式
public static final String CODE_TYPE = "UTF-8";
//填充类型 AES/ECB/PKCS5Padding AES/ECB/ISO10126Padding
public static final String AES_TYPE = "AES/ECB/PKCS5Padding";
// String aesKey = "Sxygsj!2q";
/**
* 自定义内容加盐,生成AES秘钥
*/
public static String generateAESKey(){
return DigestUtils.md5Hex(getSalt(6)).substring(8, 24);
}
/**
* 随机生成加盐类
*/
public static String getSalt(int n){
char[] chars = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+").toCharArray();
StringBuilder stringBuilder = new StringBuilder();
SecureRandom random = new SecureRandom();
for(int i = 0; i < n; i++){
stringBuilder.append(chars[random.nextInt(chars.length)]);
}
return stringBuilder.toString();
}
/**
* 加密
* @param clearText 明文
* @param aesKey AES秘钥
* @return 加密串
*/
public static String encryptAes(String clearText, String aesKey) {
try {
SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_TYPE);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(clearText.getBytes(CODE_TYPE));
return new BASE64Encoder().encode(encryptedData);
} catch (Exception e) {
throw new RuntimeException("加密失败", e);
}
}
/**
* 解密
* @param encryptText 密文
* @param aesKey AES秘钥
* @return 解密串
*/
public static String decryptAes(String encryptText, String aesKey) {
try {
byte[] byteMi = new BASE64Decoder().decodeBuffer(encryptText);
SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_TYPE);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(byteMi);
return new String(decryptedData, CODE_TYPE);
} catch (Exception e) {
throw new RuntimeException("解密失败", e);
}
}
public static void main(String[] args) {
String aesKey = generateAESKey();
String json = "123456";
System.out.println("字符串:" + json);
String encrypt = encryptAes(json, aesKey);
System.out.println("加密后字符串:" + encrypt);
System.out.println("解密后字符串:" + decryptAes(encrypt, aesKey));
}
}