import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class Base64EncryptionExample { private static final String KEY = "mySecretKey"; public static String encrypt(String data) { try { SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedData = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encryptedData); } catch (Exception e) { e.printStackTrace(); return null; } } public static String decrypt(String encryptedData) { try { SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decodedData = Base64.getDecoder().decode(encryptedData); byte[] decryptedData = cipher.doFinal(decodedData); return new String(decryptedData); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { String data = "Hello, World!"; String encryptedData = encrypt(data); System.out.println("Encrypted Data: " + encryptedData); String decryptedData = decrypt(encryptedData); System.out.println("Decrypted Data: " + decryptedData); } }


上一篇:
下一篇:
切换中文