Java实现使用PACS1_PADDING 填充方式,输出类型为base64 字符集为utf-8 进行AES加密
时间: 2024-03-28 17:37:06 浏览: 55
以下是Java代码示例,使用PKCS1_PADDING填充方式,输出类型为Base64,字符集为UTF-8进行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 {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String CHARSET = "UTF-8";
public static String encrypt(String data, String key, String iv) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(CHARSET), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(CHARSET));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(data.getBytes(CHARSET));
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String data, String key, String iv) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(CHARSET), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(CHARSET));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data));
return new String(decrypted, StandardCharsets.UTF_8);
}
}
```
其中,data为需要加密的明文字符串,key为AES加密密钥,iv为AES加密向量。调用示例:
```java
String data = "Hello, world!";
String key = "0123456789abcdef"; // 16字节的AES加密密钥
String iv = "0123456789abcdef"; // 16字节的AES加密向量
String encrypted = AesUtil.encrypt(data, key, iv);
System.out.println("Encrypted: " + encrypted);
String decrypted = AesUtil.decrypt(encrypted, key, iv);
System.out.println("Decrypted: " + decrypted);
```
输出结果:
```
Encrypted: 7GJ3+5LJUOJL/HB5TQJlMg==
Decrypted: Hello, world!
```
注意:使用AES/CBC模式时需要指定一个16字节的加密向量,向量不能重复使用,不同的数据需要使用不同的向量。密钥和向量需要保密存储,不要泄露。
阅读全文