源码
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AesEncrypt {
public static void main(String[] args) throws Exception {
// 原文
String data = "AES加密";
// 定义key
// String key = "12345678123456781234567812345678";
String key = generateAESKey();
String encryptCotent = aesEncrypt(data, key);
System.out.println("密文:" + encryptCotent);
String decryptCotent = aesDecrypt(encryptCotent, key);
System.out.println("明文:" + decryptCotent);
}
/**
* AES加密
*
* @param content 明文
* @param aesKey 密钥
* @return 加密后的密文内容
* @throws Exception
*/
public static String aesEncrypt(String content, String aesKey) throws Exception {
// 创建加密规则
byte[] bytesKey = Base64.decodeBase64(aesKey.getBytes("utf-8"));
SecretKeySpec secretKeySpec = new SecretKeySpec(bytesKey, "AES");
// 创建加密对象
Cipher cipher = Cipher.getInstance("AES");
// 进行加密初始化
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// 调用加密方法
// 参数为原文的字节数组
byte[] result = cipher.doFinal(content.getBytes("utf-8"));
return Base64.encodeBase64String(result);
}
/**
* AES解密
*
* @param content 密文
* @param aesKey 密钥
* @return 解密后的明文内容
* @throws Exception
*/
public static String aesDecrypt(String content, String aesKey) throws Exception {
byte[] bytesKey = Base64.decodeBase64(aesKey.getBytes("utf-8"));
// 解密规则
SecretKeySpec secretKey = new SecretKeySpec(bytesKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(content.getBytes("utf-8")));
return new String(result);
}
/**
* 生成AES密钥
*/
public static String generateAESKey() throws Exception {
// 密钥生成器对象
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
// 生成AES密钥
SecretKey key = keyGenerator.generateKey();
// 获取AES密钥的字节数组
byte[] keyExternal = key.getEncoded();
return Base64.encodeBase64String(keyExternal);
}
}
<!-- base64依赖 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
网友评论