java aes加密解密工具类
时间: 2023-10-15 07:03:38 浏览: 98
以下为Java的AES加密解密工具类:
```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";
/**
* 加密
* @param data 待加密的字符串
* @param key 密钥
* @param iv 向量
* @return 加密后的字符串
*/
public static String encrypt(String data, String key, String iv) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(data.getBytes(CHARSET));
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
* @param data 待解密的字符串
* @param key 密钥
* @param iv 向量
* @return 解密后的字符串
*/
public static String decrypt(String data, String key, String iv) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data));
return new String(decrypted, CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
String data = "Hello, world!";
String key = "1234567890123456";
String iv = "1234567890123456";
String encrypted = AESUtil.encrypt(data, key, iv);
String decrypted = AESUtil.decrypt(encrypted, key, iv);
System.out.println("明文:" + data);
System.out.println("加密后:" + encrypted);
System.out.println("解密后:" + decrypted);
}
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)