/**
* <p>Description: AES 算法加密</p>
*
* @author XXX
* @date 2020/11/25 21:56
* @since JDK1.8
*/
public class AESEncryption {
private static Base64.Encoder encoder = Base64.getEncoder();
private static Base64.Decoder decoder = Base64.getDecoder();
private static String aesEncrypt(String text, String originKey) throws Exception {
//获取加密算法工具类对象
Cipher cipher = Cipher.getInstance("AES");
//对原始秘钥处理后的秘钥
SecretKeySpec key = getKey(originKey);
cipher.init(Cipher.ENCRYPT_MODE, key);
//用加密算法对明文进行加密
byte[] bytes = cipher.doFinal(text.getBytes());
return new String(encoder.encode(bytes));
}
private static String aesDecrypt(String encrypt, String originKey) throws Exception {
//获取加密算法工具类对象
Cipher cipher = Cipher.getInstance("AES");
//对原始秘钥处理后的秘钥
SecretKeySpec key = getKey(originKey);
cipher.init(Cipher.DECRYPT_MODE, key);
//用加密算法对明文进行加密
byte[] bytes = cipher.doFinal(decoder.decode(encrypt.getBytes()));
return new String(bytes);
}
private static SecretKeySpec getKey(String originKey) {
//AES 算法要求为128位,16个字节
byte[] buffer = new byte[16];
byte[] bytes = originKey.getBytes();
for (int i = 0; i < 16 && i < bytes.length; i++) {
buffer[i] = bytes[i];
}
//根据原始秘钥构造一个新的秘钥,要求 buffer.length = 16
return new SecretKeySpec(buffer, "AES");
}
public static void main(String[] args) throws Exception {
String originKey = "12345678912312312";
String text = "hello";
System.out.println("加密前:" + text);
String encrypt = aesEncrypt(text, originKey);
System.out.println("加密后:" + encrypt);
String decrypt = aesDecrypt(encrypt, originKey);
System.out.println("解密后:" + decrypt);
}
}
03_AES算法加密
最新推荐文章于 2024-04-25 17:37:33 发布