[Java] 纯文本查看 复制代码 import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
// 原始数据
String data = "Hello, World!";
// 密钥,这里假设密钥是16字节的字符串
String key = "ThisIsASecretKey";
// 加密
String encryptedData = encrypt(data, key);
System.out.println("加密后的数据:" + encryptedData);
// 解密
String decryptedData = decrypt(encryptedData, key);
System.out.println("解密后的数据:" + decryptedData);
}
public static String encrypt(String data, String key) throws Exception {
byte[] keyBytes = key.getBytes("UTF-8");
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));
return Base64.encodeBase64String(encryptedBytes);
}
public static String decrypt(String encryptedData, String key) throws Exception {
byte[] keyBytes = key.getBytes("UTF-8");
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] encryptedBytes = Base64.decodeBase64(encryptedData);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, "UTF-8");
}
}
|