//使用安全数可以增加
SECURITY_STR 安全系数
package demo.security;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* @author God
* AES加密解密工具类
*/
public class AESUtil {
//加密模式
public static final String ALGORITHM_AES="AES";
//安全数
public static final String SECURITY_STR="zhangsan";
/**
* 加密
* @param security_str
* @param clearText
* @return
*/
public static byte[] AESEncode(String security_str,String clearText){
byte[] cipherBytes=null;
try {
// 1.构造密钥生成器,指
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_AES);
// 2.初始化秘钥生成器 加安全数
keyGenerator.init(128, new SecureRandom(security_str.getBytes()));
//获取安全秘钥
SecretKey secretKey = keyGenerator.generateKey();
///生成秘钥自己数组
byte[] secretKeyBytes = secretKey.getEncoded();
//根据字节数组生成AES秘钥
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, ALGORITHM_AES);
// 根据AES生成密码器
Cipher cipher = Cipher.getInstance(ALGORITHM_AES);
//初始化密码器 加密模式,secretKeySpec
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
//将明文进行自己数组加密处理
cipherBytes=cipher.doFinal(clearText.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherBytes;
}
/**
* 解密 安全数 加密的数组
* @return
*/
public static byte[] AESDecode(String security_str,byte [] cipherBytes){
byte[] clearTextBytes=null;
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_AES);
keyGenerator.init(128, new SecureRandom(security_str.getBytes()));
SecretKey secretKey = keyGenerator.generateKey();
byte[] secretKeyBytes = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes,ALGORITHM_AES);
Cipher cipher = Cipher.getInstance(ALGORITHM_AES);// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化
clearTextBytes = cipher.doFinal(cipherBytes);
} catch (Exception e) {
e.printStackTrace();
}
return clearTextBytes;
}
/**
* 测试AES加密解密
* @param args
*/
public static void main(String[] args) {
String clearText="老司机开车了";
System.out.println("明文是_____:"+clearText);
//加密
System.out.println("机密后的密文是___________:"+AESEncode(SECURITY_STR, "老司机开车了"));
byte[]bytes=AESDecode(SECURITY_STR, AESEncode(SECURITY_STR, "老司机开车了"));
System.out.println("解析的明文是___:"+new String(bytes));
}
}