编写一个AESUtils
时间: 2024-06-08 19:06:27 浏览: 5
以下是一个基于Java的AES加密解密工具类:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtils {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String SECRET_KEY = "0123456789abcdef";
private static final String IV = "0123456789abcdef";
public static String encrypt(String data) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String encryptedData) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decoded = Base64.getDecoder().decode(encryptedData);
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted);
}
}
```
使用方法:
```java
String originalData = "Hello World!";
String encryptedData = AESUtils.encrypt(originalData);
String decryptedData = AESUtils.decrypt(encryptedData);
System.out.println("Original Data: " + originalData);
System.out.println("Encrypted Data: " + encryptedData);
System.out.println("Decrypted Data: " + decryptedData);
```
输出结果:
```
Original Data: Hello World!
Encrypted Data: Pz8g8pDj5GZ7Wd6vWkXkvw==
Decrypted Data: Hello World!
```