java 实现AES加密算法
时间: 2023-08-02 19:07:50 浏览: 121
下面是一个简单的 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 AESUtil {
public static String encrypt(String plaintext, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(plaintext.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String ciphertext, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decoded = Base64.getDecoder().decode(ciphertext);
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String plaintext = "Hello, world!";
String key = "0123456789abcdef";
String iv = "fedcba9876543210";
String ciphertext = encrypt(plaintext, key, iv);
System.out.println("Ciphertext: " + ciphertext);
String decrypted = decrypt(ciphertext, key, iv);
System.out.println("Decrypted: " + decrypted);
}
}
```
注意:这只是一个简单的示例代码,实际使用中应该考虑更多的安全因素,比如密钥的生成和管理、IV 的随机性等。
阅读全文