java aes256加密解密
时间: 2024-03-12 11:42:10 浏览: 19
Java AES256加密解密是一种常用的对称加密算法,它使用256位的密钥对数据进行加密和解密。下面是Java中使用AES256进行加密解密的基本步骤:
1. 导入相关的类库:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
```
2. 定义加密解密方法:
```java
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
```
3. 使用加密解密方法:
```java
public class Main {
public static void main(String[] args) {
try {
String data = "Hello, World!";
String key = "0123456789abcdef0123456789abcdef"; // 256位密钥
String encryptedData = AESUtil.encrypt(data, key);
System.out.println("加密后的数据:" + encryptedData);
String decryptedData = AESUtil.decrypt(encryptedData, key);
System.out.println("解密后的数据:" + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码演示了如何使用Java进行AES256加密解密。需要注意的是,密钥的长度必须是256位(32字节),并且在实际应用中应该使用安全的方式来保存和传输密钥。