java实现aes-128加密算法
时间: 2024-02-23 11:55:14 浏览: 200
Java实现AES加密算法
5星 · 资源好评率100%
Java中可以使用javax.crypto包来实现AES-128加密算法。下面是一个简单的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static String encrypt(String plaintext, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String ciphertext, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
try {
String plaintext = "Hello, World!";
String key = "0123456789abcdef"; // 16字节的密钥
String ciphertext = AESUtil.encrypt(plaintext, key);
System.out.println("加密后的密文:" + ciphertext);
String decryptedText = AESUtil.decrypt(ciphertext, key);
System.out.println("解密后的明文:" + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意:在实际使用中,应该使用更安全的方式来存储密钥,例如使用密钥管理系统(Key Management System)来保护密钥的安全性。
阅读全文