java实现aes加解密
时间: 2023-11-29 21:05:23 浏览: 77
java 实现aes加解密算法
以下是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";
/**
* AES加密
*
* @param data 待加密的数据
* @param key 密钥
* @param iv 向量
* @return 加密后的数据
* @throws Exception
*/
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(CHARSET));
return Base64.getEncoder().encodeToString(encrypted);
}
/**
* AES解密
*
* @param data 待解密的数据
* @param key 密钥
* @param iv 向量
* @return 解密后的数据
* @throws Exception
*/
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);
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) throws Exception {
String data = "Hello, world!";
String key = "0123456789abcdef";
String iv = "0123456789abcdef";
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);
}
}
```
阅读全文