AES即高级加密算法标准,AES算法作为新一代的数据加密标准,汇聚了安全性、高性能、高效率、易用和灵活等优点,设计有三个密钥长度(128、192、256位),比DES算法加密强度更高,更为安全。
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* 对称加密-aes
* @author a
*
*/
public class AESUtil {
public static void main(String[] args) throws Exception {
//910ffbf5c2b76bbf5ced93ba566f62a2
SecretKey loadKeyAES = loadKeyAES("910ffbf5c2b76bbf5ced93ba566f62a2");
byte[] encryptAES = encryptAES("123456".getBytes("utf8"), loadKeyAES);//加密后字符串:9f0457b479b630c2b9c4c4babcf314ec
decryptAES(Byte2hex.hex2bytes("7db15434175d9abe2c4ee8cf431dfa6f"),loadKeyAES);//十六进制字符串转为二进制
decryptAES(encryptAES,loadKeyAES);
}
//加密
public static byte[] encryptAES(byte[] source,SecretKey key) throws Exception{
Cipher cipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(source);
String encryptstr = Byte2hex.bytes2hex(doFinal);
System.out.println("加密后字符串:"+encryptstr);
return doFinal;
}
//解密密
public static void decryptAES(byte[] source,SecretKey key) throws Exception{
Cipher cipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(source);
System.out.println("解密后字符串:"+new String(doFinal, "utf8"));//二进制转为字符串
}
//生成AES密钥
public static String genKeyAES() throws Exception{
KeyGenerator keyGen=KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey key = keyGen.generateKey();
String base64str = Byte2hex.bytes2hex(key.getEncoded());
System.out.println("生成密钥:"+base64str);
return base64str;
}
//将密钥生成key
public static SecretKey loadKeyAES(String Base64Str) throws Exception{
byte[] bytes = Byte2hex.hex2bytes(Base64Str);
SecretKey key=new SecretKeySpec(bytes, "AES");
return key;
}
}