package org.example.test;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) {
try {
SecretKey key = generateAESKey(256);
System.out.println("Generated AES Key: " + key);
String s = Base64.getEncoder().encodeToString(key.getEncoded());
System.out.println(s);
SecretKeySpec aes = new SecretKeySpec(Base64.getDecoder().decode(s), "AES");
String data = "This is a secret message.";
String encryptedData = encrypt(data, aes);
System.out.println("Encrypted Data: " + encryptedData);
String decryptedData = decrypt(encryptedData, aes);
System.out.println("Decrypted Data: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SecretKey generateAESKey(int keySize) throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(keySize);
return keyGen.generateKey();
}
public static String encrypt(String data, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}
public static String decrypt(String encryptedData, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData);
}
}