When I create an RSA keypair should I be be doing
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
save("public.key",publicKey.getEncoded())
save("private.key",privateKey.getEncoded())
OR
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),RSAPrivateKeySpec.class);
saveToFile("public.key", pub.getModulus(),pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(),priv.getPrivateExponent());
Which is better and what is the difference?
For public keys, it doesn’t make much difference. For private keys, getEncoded() returns much more information than the private key.
Here is the ASN.1 schema for RSA Private Key,
Those extra parameters will speed up private key operations considerably. So you should always use
getEncoded().