package cn.com.pubinfo.sifa.mediate.util;
import org.apache.shiro.codec.Base64;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESUtils {
/**
* 密钥算法
*/
private static final String ALGORITHM = "AES";
/**
* 加解密算法/工作模式/填充方式
*/
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
/**
* SecretKeySpec类是KeySpec接口的实现类,用于构建秘密密钥规范
*/
private SecretKeySpec key;
private SecretKey key2;
public AESUtils(String hexKey) {
try {
//创建密钥生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
//初始化密钥
keyGenerator.init(128,new SecureRandom(hexKey.getBytes()));
//生成密钥
key2 = keyGenerator.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
key = new SecretKeySpec(hexKey.getBytes(), ALGORITHM);
}
/**
* AES加密
* @param data
* @return
* @throws Exception
*/
public String encryptData(String data) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key2);// 初始化
return new Base64().encodeToString(cipher.doFinal(data.getBytes()));
}
/**
* AES解密
* @param base64Data
* @return
* @throws Exception
*/
public String decryptData(String base64Data) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.DECRYPT_MODE, key2);
return new String(cipher.doFinal(new Base64().decode(base64Data)));
}
public static String decrypt(String base64Data,String key) {
AESUtils aesUtil = new AESUtils(key);
String result = null;
try {
result = aesUtil.decryptData(base64Data);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String encrypt(String data,String key) {
AESUtils aesUtil = new AESUtils(key);
String result = null;
try {
result = aesUtil.encryptData(data);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* hex字符串 转 byte数组
* @param s
* @return
*/
private static byte[] hex2byte(String s) {
if (s.length() % 2 == 0) {
return hex2byte (s.getBytes(), 0, s.length() >> 1);
} else {
return hex2byte("0"+s);
}
}
private static byte[] hex2byte (byte[] b, int offset, int len) {
byte[] d = new byte[len];
for (int i=0; i<len*2; i++) {
int shift = i%2 == 1 ? 0 : 4;
d[i>>1] |= Character.digit((char) b[offset+i], 16) << shift;
}
return d;
}
public static void main(String[] args) throws Exception {
AESUtils util = new AESUtils("ZMIQHUNJIZIHQIHEXFBO"); // 密钥
System.out.println("cardNo:"+util.encryptData("{\"serialNumber\":\"330211JD04000017092001003JKLBNTH\",\"status\":36}")); // 加密
System.out.println("exp:"+util.decryptData("psVhPX1LJxW90Ol7LsCLTSAWNHwbsW90fWdrJylc+y+L5TTkMPj1N7gCb4BGC73RDPpaX1pS4XVMlP67CQTzow==")); // 解密
}
}
基于Java的AES加解密demo
最新推荐文章于 2021-08-22 10:42:33 发布