java如何实现AES加密
时间: 2023-06-01 18:06:01 浏览: 284
Java可以使用javax.crypto包来实现AES加密,具体步骤如下:
1. 生成一个AES密钥。
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
2. 根据密钥初始化加密器。
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
3. 进行加密操作。
byte[] encryptedBytes = cipher.doFinal(sourceBytes);
完整代码如下:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AesEncryptUtil {
/**
* 生成AES密钥
*
* @param keySize 密钥长度(单位:位)
* @return 密钥
* @throws Exception 异常
*/
public static byte[] generateAesKey(int keySize) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(keySize);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
}
/**
* AES加密
*
* @param sourceBytes 待加密的字节数组
* @param aesKeyBytes 密钥字节数组
* @return 加密后的字节数组
* @throws Exception 异常
*/
public static byte[] encrypt(byte[] sourceBytes, byte[] aesKeyBytes) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(aesKeyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(sourceBytes);
}
/**
* AES解密
*
* @param encryptedBytes 待解密的字节数组
* @param aesKeyBytes 密钥字节数组
* @return 解密后的字节数组
* @throws Exception 异常
*/
public static byte[] decrypt(byte[] encryptedBytes, byte[] aesKeyBytes) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(aesKeyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(encryptedBytes);
}
/**
* 将字节数组转换为Base64编码的字符串
*
* @param bytes 字节数组
* @return Base64编码的字符串
*/
public static String base64Encode(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
/**
* 将Base64编码的字符串解码为字节数组
*
* @param base64String Base64编码的字符串
* @return 字节数组
*/
public static byte[] base64Decode(String base64String) {
return Base64.getDecoder().decode(base64String);
}
public static void main(String[] args) throws Exception {
byte[] aesKeyBytes = generateAesKey(128);
String sourceString = "Hello, World!";
byte[] sourceBytes = sourceString.getBytes(StandardCharsets.UTF_8);
byte[] encryptedBytes = encrypt(sourceBytes, aesKeyBytes);
String encryptedBase64String = base64Encode(encryptedBytes);
byte[] encryptedBytesFromBase64 = base64Decode(encryptedBase64String);
byte[] decryptedBytes = decrypt(encryptedBytesFromBase64, aesKeyBytes);
System.out.println("原文:" + sourceString);
System.out.println("加密后的Base64字符串:" + encryptedBase64String);
System.out.println("解密后的原文:" + new String(decryptedBytes, StandardCharsets.UTF_8));
}
}
阅读全文