用Java实现AES/ECB/PKCS5Padding加密和解密
时间: 2024-01-27 20:05:06 浏览: 163
JAVA、Python、PHP一致的 "任意长度secret秘钥" 加解密AES/ECB/PKCS5Padding算法实现代码
好的,下面是Java实现AES/ECB/PKCS5Padding加密和解密的示例代码:
```
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
// 加密
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
// 解密
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decrypted);
}
}
```
使用示例:
```
public static void main(String[] args) throws Exception {
String data = "Hello, world!";
String key = "0123456789abcdef";
String encryptedData = AESUtil.encrypt(data, key);
String decryptedData = AESUtil.decrypt(encryptedData, key);
System.out.println("加密前:" + data);
System.out.println("加密后:" + encryptedData);
System.out.println("解密后:" + decryptedData);
}
```
输出:
```
加密前:Hello, world!
加密后:qVeqhVSSSmYZQgz6H+JYUA==
解密后:Hello, world!
```
注意事项:
1. key 长度必须为16位。
2. 为了方便起见,这里使用了 Base64 编码。如果需要更高的安全性,可以使用 Hex 编码。
阅读全文