tags:

views:

36

answers:

1

Dear all, 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 stored elsewhere

A: 
PublicKey pubKey = myPair.getPublic();
byte[] keyBytes = pubKey.getEncoded();

Save the keyBytes as binary file or store it somewhere.

Do this to reconstruct the key,

 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
 X509EncodedKeySpec pubKeySpec 
     = new X509EncodedKeySpec(keyBytes);
 PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
ZZ Coder
That what I was looking for