Here you can find the source of generateKey()
public static void generateKey()
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; public class Main { /**// w w w . j a va2 s.co m * String to hold name of the encryption algorithm. */ public static final String ALGORITHM = "RSA"; /** * String to hold the name of the private key file. */ public static final String PRIVATE_KEY_FILE = "E:/1AARedMedicaWakeUp/keys/private.key"; /** * String to hold name of the public key file. */ public static final String PUBLIC_KEY_FILE = "E:/1AARedMedicaWakeUp/keys/public.key"; public static void generateKey() { try { final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM); keyGen.initialize(512); final KeyPair key = keyGen.generateKeyPair(); File privateKeyFile = new File(PRIVATE_KEY_FILE); File publicKeyFile = new File(PUBLIC_KEY_FILE); // Create files to store public and private key if (privateKeyFile.getParentFile() != null) { privateKeyFile.getParentFile().mkdirs(); } privateKeyFile.createNewFile(); if (publicKeyFile.getParentFile() != null) { publicKeyFile.getParentFile().mkdirs(); } publicKeyFile.createNewFile(); // Saving the Public key in a file ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFile)); publicKeyOS.writeObject(key.getPublic()); publicKeyOS.close(); // Saving the Private key in a file ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFile)); privateKeyOS.writeObject(key.getPrivate()); privateKeyOS.close(); // Key pubKey = key.getPublic(); // Key privKey = key.getPrivate(); //byte[] privateKeyBytes = privKey.getEncoded(); // byte[] publicKeyBytes = pubKey.getEncoded(); //chiperTexto = new String(Base64.getEncoder().encode(publicKeyBytes)); //chiperTexto2 = new String(Base64.getEncoder().encode(privateKeyBytes)); // System.out.println("pubKey1: "+chiperTexto); // System.out.println("privKey1: "+chiperTexto2); } catch (NoSuchAlgorithmException | IOException e) { } } }