/*  RAS 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.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

import javax.crypto.Cipher;

public class RSA 
{
    
    private static PrivateKey privateKey;
    
    private static PublicKey publicKey;
    
    public static void main( String[] args ) throws Exception 
    {
        String plainText ="Dies ist eine streng geheime Nachricht!!!";
        
        generateKey();
        System.out.println("Original String to encrypt - " + plainText);
        String chiperText = encrypt(plainText);
        System.out.println("Encrypted String - " + chiperText);
        String decryptedMessage = decrypt(chiperText);
        System.out.println("After decryption - " + decryptedMessage);
    }
    
    public static void generateKey() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        KeyPair pair = generator.generateKeyPair();
        privateKey = pair.getPrivate();
        publicKey = pair.getPublic();
    } // generateKey
    
    public static String encrypt(String message) throws Exception
    {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(message.getBytes("UTF-8"));
        
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(encryptedBytes);
    } // encrypt
    
    public static String decrypt(String encryptedMessage) throws Exception{
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decryptedMessage = cipher.doFinal(decoder.decode(encryptedMessage));
        return new String(decryptedMessage);
    } // decrypt
}
