AES(Advanced Encryption Standard),高级加密标准,对称算法,是下一代的加密算法标准,速度快,安全级别高,在21世纪AES 标准的一个实现是 Rijndael 算法;
AES加密算法是密码学中的高级加密标准,该加密算法采用对称分组密码体制,密钥长度的最少支持为128、192、256,分组长度128位,算法应易于各种硬件和软件实现。这种加密算法是美国联邦政府采用的区块加密标准,这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。
它适用于敏感内容进行加密传输,防止被窃取。
public class AESUtil {
private static String AES= "AES";
private static final String defaultCharset= "utf-8";
public static class Factory{
//此方法可以被改写,定义自己的密钥生成策略
public static String genKey(){
try {
KeyGenerator keyGenerator= KeyGenerator.getInstance(AES);
keyGenerator.init(128);
SecretKey secretKey= keyGenerator.generateKey();
return parseByte2HexStr(secretKey.getEncoded());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
throw new RuntimeException("generate AES key error.");
}
}
public static String enAES(String data,String key){
try {
Cipher cipher = Cipher.getInstance(AES);
byte[] byteContent = data.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
byte[] result = cipher.doFinal(byteContent);
return new String(Base64.getEncoder().encode(result));
} catch (Exception ex) {
ex.printStackTrace();
}
throw new RuntimeException("enAES error.");
}
public static String deAES(String data,String key){
try {
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
byte[] result = cipher.doFinal(Base64.getDecoder().decode(data.getBytes(defaultCharset)));
return new String(result, "utf-8");
} catch (Exception ex) {
ex.printStackTrace();
}
throw new RuntimeException("deAES error.");
}
/**
* 二进制转16进制
* @param bytes
* @return
*/
private static String parseByte2HexStr(byte[] bytes){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
private static SecretKeySpec getSecretKey(final String password) {
try {
KeyGenerator kg = KeyGenerator.getInstance(AES);
//AES 要求密钥长度为 128
kg.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), AES);
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
throw new RuntimeException("getSecretKey error.");
}
public static void main(String[] args) {
String key= Factory.genKey();
System.out.println("key: "+key);
String wl= "{welcome to 中国.}";
String ens= enAES(wl,key);
System.out.println("after enAES: "+ens);
String des= deAES(ens,key);
System.out.println("after deAES: "+des);
}
}
网友评论