import java.util.Arrays;
import java.security.*;
import java.util.*;
import javax.crypto.*;

public class RSAtest {
    public static void main (String[] args) throws Exception {
        String text = "This is a simple text Message.";

        System.out.println("UnEncryptedage: "+ text + "\n");
        System.out.println("UnEncryptedage as Array: "+ Arrays.toString(text.getBytes()) + "\n");

		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(2048);
		KeyPair key = keyGen.generateKeyPair();

        //Encrypted data is binary data
        String encryptTextA = Arrays.toString(encryptRSA(text,key));
        System.out.println("Encryptedage as Array: "+ encryptTextA + "\n");
        String encryptText = new String(encryptRSA(text,key), "UTF-8");
        System.out.println("Encryptedage as String: "+ encryptText + "\n");

        String decryptTextA = Arrays.toString(decryptRSA(encryptRSA(text,key),key));
        System.out.println("Decryptedage as Array: "+ decryptTextA + "\n");
        String decryptText = new String(decryptRSA(encryptRSA(text,key),key), "UTF-8");
        System.out.println("Decryptedage: "+ decryptText);
    }

    public static byte[] decryptRSA(byte[] message,KeyPair key) throws Exception {
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		PrivateKey privateKey = key.getPrivate();
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		byte [] plainBytes = cipher.doFinal(message);
		String plainText = new String(plainBytes, "UTF8").toString();
		System.out.println("plainText: "+ plainText);
		return plainBytes;
		
    }

    public static byte[] encryptRSA(String message,KeyPair key) throws Exception {

        		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
				PublicKey publicKey = key.getPublic();
				cipher.init(Cipher.ENCRYPT_MODE, publicKey);
				byte [] cipherBytes = cipher.doFinal(message.getBytes());
				String cipherText = new String(cipherBytes,"UTF8").toString();
				System.out.println("cipherText: "+ cipherText);
				return cipherBytes;
    }
}