java AES 加密工具栏
时间: 2023-09-02 21:12:35 浏览: 141
以下是一个简单的 Java AES 加密工具类,可以用于加密和解密:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
private static final String SECRET_KEY = "mySecretKey12345";
private static final String INIT_VECTOR = "myInitVector1234";
public static String encrypt(String value) {
try {
IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes("UTF-8"));
SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes("UTF-8"));
SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
```
使用示例:
```java
String originalString = "This is a secret message.";
String encryptedString = AESUtil.encrypt(originalString);
String decryptedString = AESUtil.decrypt(encryptedString);
System.out.println("Original string: " + originalString);
System.out.println("Encrypted string: " + encryptedString);
System.out.println("Decrypted string: " + decryptedString);
```
输出:
```
Original string: This is a secret message.
Encrypted string: MWvSZ2y0nBtZvF9vz1+UeRjyz6qI1sGhKJw1XoTZ4Tc=
Decrypted string: This is a secret message.
```
阅读全文