KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"RSA\");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.ge
I use the following code to convert a PubliKey
to PEM Base64 format
String publicKeyString = javax.xml.bind.DatatypeConverter.printBase64Binary(publicKey.getEncoded());
I hope it helps.
Depends on what do you want to do with the serialized representation. If the consumer is no one but your own program, feel free to roll your own implementation. A public RSA key consists of two integers - exponent and modulus. Modulus is large - around 1024 bits, exponent is typically on the order of 17 bits. Both are available as BigInteger
objects if you cast your public key object to RSAPublicKey
.
So, to recap:
RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();
return publicKey.getModulus().toString() + "|" +
publicKey.getPublicExponent().toString();
That's sufficient to restore the key. To deserialize:
String []Parts = MyKeyString.split("\\|");
RSAPublicKeySpec Spec = new RSAPublicKeySpec(
new BigInteger(Parts[0]),
new BigInteger(Parts[1]));
return KeyFactory.getInstance("RSA").generatePublic(Spec);
If the key needs to be passed to third party software, you better serialize to a standard format - PEM or DER.
Asymmetric keys like those from RSA are usually stored in X509 format. Therefor you can use X509EncodedKeySpec
instead.
A simple example is already in the Java 7 JavaDoc (just replace DSA with RSA): http://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
If you need to deserialize the private from byte[]
, I've found that you must use PKCS8EncodedKeySpec
.