// 加密
public static String encrypt(String plainText, String secretKey) {
try {
SecretKeySpec secretKeySpec = new
SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8),
AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes =
cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 解密
public static String decrypt(String encryptedText, String secretKey)
{
try {
SecretKeySpec secretKeySpec = new
SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8),
AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] encryptedBytes =
Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String plainText = "Hello, World!";
String secretKey = "this-is-a-secret-key";
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);