title: How to save and re-use keypairs in Java asymmetric encryption?
body: <p>I've written code that generates the key pairs, but was wondering if there's any way to save and re-use them? </p>
  
  <p>Here is the code that generaes the pair:</p>
  
  <p>public static void main(String[] args) throws Exception {</p>
  
  <pre><code>    String plainText = "Hello world";
  
      Map&lt;String, Object&gt; keys = getRSAKeys();
  
      PrivateKey privateKey = (PrivateKey) keys.get("private");
      PublicKey publicKey = (PublicKey) keys.get("public");
  
      System.out.println(privateKey.getEncoded());
  
      System.out.println(publicKey.getEncoded());
  
  
  
      String encrypted = encryptMessage(plainText, privateKey);
  
  
      System.out.println(encrypted);
  
      String decrypted = decryptMessage(plainText, publicKey, encrypted);
  
      System.out.println(decrypted);
  
  }
  
  private static Map&lt;String, Object&gt; getRSAKeys() throws Exception {
  
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      PrivateKey privateKey = keyPair.getPrivate();
      PublicKey publicKey = keyPair.getPublic();
      Map&lt;String, Object&gt; keys = new HashMap&lt;String, Object&gt;();
      keys.put("private", privateKey);
      keys.put("public", publicKey);
  
      return keys;
  
  }
  </code></pre>