// Java program to create a // asymmetric key import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.util.Scanner; import javax.crypto.Cipher; // Class to create an asymmetric key public class Asymmetric { private static final String RSA = "RSA";//algoritmo rsa // Generating public and private key // using RSA algorithm. public static KeyPair generateRSAKkeyPair()throws Exception{ SecureRandom secureRandom = new SecureRandom(); //random ma piĆ¹ sicuro KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);//crea una chiave da usare per l'rsa keyPairGenerator.initialize(2048, secureRandom);//keysize return keyPairGenerator.generateKeyPair();//crea la coppia d chiavi } // Encryption function which converts // the plainText into a cipherText // using private Key. public static byte[] do_RSAEncryption(String plainText,PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance(RSA); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(plainText.getBytes()); } // Decryption function which converts // the ciphertext back to the // original plaintext. public static String do_RSADecryption(byte[] cipherText,PublicKey publicKey)throws Exception{ Cipher cipher = Cipher.getInstance(RSA); cipher.init(Cipher.DECRYPT_MODE,publicKey); byte[] result = cipher.doFinal(cipherText); return new String(result); } // Driver code public static void main(String args[]) throws Exception { KeyPair keypair = generateRSAKkeyPair(); //RSA private keys are encoded in PKCS#8 format, and public keys are encoded in X.509 format //DatatypeConverter.printHexBinary //chiavi System.out.println("Public Key is: " + keypair.getPublic().getEncoded()); System.out.println("Private Key is: " + keypair.getPrivate().getEncoded()); String plainText = "This is the PlainText I want to Encrypt using RSA."; byte[] cipherText= do_RSAEncryption(plainText,keypair.getPrivate()); System.out.print("The Encrypted Text is: "); System.out.println(cipherText); String decryptedText = do_RSADecryption(cipherText,keypair.getPublic()); System.out.println("The decrypted text is: "+ decryptedText); } }