一、AES简介
高级加密标准(AES,Advanced Encryption Standard)为最常见的对称加密算法。
对称加密算法:加密和解密用相同的密钥。
java代码
package com.aes;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String CHARSET = "UTF-8";
private static final String KEY = "1234567891234567";
/**
* 实现数据的AES加密
* @param content
* @param key
* @return
* @throws Exception
*/
public static String encrypt(String content) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(CHARSET), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(content.getBytes(CHARSET));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
/**
* 实现AES解密
* @param content
* @param key
* @return
* @throws Exception
*/
public static String decrypt(String content) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(CHARSET), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(content);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, CHARSET);
}
}