OneCompiler

aes

105

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class RijndaelAES {

private static final String ALGORITHM = "AES";

// 16-byte key for AES-128
private static final String SECRET_KEY = "1234567890abcdef"; // Must be 16 chars

public static String encrypt(String plainText) throws Exception {
    SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
    Cipher cipher = Cipher.getInstance(ALGORITHM); // "AES/ECB/PKCS5Padding" can also be used
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
    return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String encryptedText) throws Exception {
    SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, keySpec);

    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
    return new String(decryptedBytes);
}

public static void main(String[] args) {
    try {
        String originalText = "Hello Rijndael!";
        System.out.println("Original: " + originalText);

        String encrypted = encrypt(originalText);
        System.out.println("Encrypted: " + encrypted);

        String decrypted = decrypt(encrypted);
        System.out.println("Decrypted: " + decrypted);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}