java 写一个 AES 方法
时间: 2024-09-30 07:09:02 浏览: 27
AES(Advanced Encryption Standard),即高级加密标准,是一种常用的对称加密算法。在Java中,我们可以利用`javax.crypto.Cipher`类来实现AES加密。以下是一个简单的AES加密示例,使用了CBC模式(Cipher Block Chaining):
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
public class AESEncryption {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = "your_secret_key_128_chars".getBytes(); // 16 bytes for 128-bit key
private static final SecureRandom random = new SecureRandom();
public static String encrypt(String data) throws Exception {
IvParameterSpec iv = new IvParameterSpec(keyValue);
SecretKeySpec secretKey = new SecretKeySpec(keyValue, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM + "/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData); // 返回Base64编码以便存储或传输
}
public static String decrypt(String encryptedData) throws Exception {
byte[] encodedData = Base64.getDecoder().decode(encryptedData);
// 同样的IV用于解密
IvParameterSpec iv = new IvParameterSpec(keyValue);
SecretKeySpec secretKey = new SecretKeySpec(keyValue, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM + "/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] decryptedData = cipher.doFinal(encodedData);
return new String(decryptedData);
}
}
```
在这个例子中,你需要替换`"your_secret_key_128_chars"`为你实际使用的AES密钥。
阅读全文