RSA Public Key Export

Here is my code

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); KeyPair myPair = kpg.generateKeyPair(); PrivateKey k = myPair.getPrivate(); System.out.print(k.serialVersionUID); Cipher c = Cipher.getInstance("RSA"); c.init(Cipher.ENCRYPT_MODE, myPair.getPublic()); String myMessage = new String("Testing the message"); byte[] bytes = c.doFinal(myMessage.getBytes()); String tt = new String(bytes); System.out.println(tt); Cipher d = Cipher.getInstance("RSA"); d.init(Cipher.DECRYPT_MODE, myPair.getPrivate()); byte[] temp = d.doFinal(bytes); String tst = new String(temp); System.out.println(tst); 

My question is how can I get the public key and save it elsewhere

+4
source share
1 answer
 PublicKey pubKey = myPair.getPublic(); byte[] keyBytes = pubKey.getEncoded(); 

Save keyBytes as a binary file or save it somewhere.

Do this to restore the key,

  KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(keyBytes); PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); 
+4
source

Source: https://habr.com/ru/post/1309061/


All Articles