java使用AES/CBC/PKCS5Padding加密
时间: 2023-11-12 13:04:07 浏览: 164
java/javascript/iOS的AES加解密(AES/CBC/PKCS5Padding)
5星 · 资源好评率100%
好的,针对您的问题,我可以给出以下代码示例:
```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 ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String CHARSET = "UTF-8";
public static String encrypt(String data, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(CHARSET), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(CHARSET));
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String data, String key, String iv) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(CHARSET), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(CHARSET));
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data));
return new String(decrypted, CHARSET);
}
}
```
其中,`encrypt` 方法用于加密数据,`decrypt` 方法用于解密数据。需要传入三个参数:待加密/解密的数据、密钥和向量。
阅读全文