/*  AES encryption
 *
 *  Copyright (C) 2023  Rene Pawlitzek, Robert Schoech
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

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

public class AES 
{
    private static SecretKeySpec secretKeySpec;
    private static byte[] key;    
    
    public static void main( String[] args ) throws Exception 
    {
        String plainText ="This is my plaintext";
        System.out.println("Plaintext: " + plainText);
        String myKey = "0123456789ABCDEF";
        System.out.println("Key: " + myKey);
        key = myKey.getBytes("UTF-8");
        
        String chiperText = encrypt(plainText);
        System.out.println("Encrypted text: " + chiperText);
        System.out.println("Length in Bytes:" + (chiperText.length() / 2));
        System.out.println("Lenght in Bits:" + ((chiperText.length() / 2) * 8));
        String decryptedMessage = decrypt(chiperText);
        System.out.println("Decrypted text:" + decryptedMessage);
    }
    
    public static String encrypt(String toEncrypt) throws Exception 
    {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] cipherText = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
        
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(cipherText);
    } // encrypt
    
    public static String decrypt(String toDecrypt) throws Exception 
    {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] cipherText = cipher.doFinal(decoder.decode(toDecrypt));
        
        return new String(cipherText, "UTF8");
    } // decrypt 
}
