I wanted to ask how to retrieve the actual values of the private and public keys from the KeyPair object because i need to export them and save in a database.
It's probably easiest to use keypair.getPublic.getEncoded()
or keypair.getPrivate.getEncoded()
:
RSA private keys are encoded in PKCS#8 format, and public keys are encoded in X.509 format.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pub = keyPair.getPublic();
PrivateKey prv = keyPair.getPrivate();
byte[] pubBytes = pub.getEncoded();
byte[] prvBytes = prv.getEncoded();
// now save pubBytes or prvBytes
// to recover the key
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey prv_recovered = kf.generatePrivate(new PKCS8EncodedKeySpec(prvBytes));
PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pubBytes));
System.out.println("Private Key: \n" + prv_recovered.toString());
System.out.println("Public Key: \n" + pub_recovered.toString());
You can simply downcast to RSAPrivateKey
and RSAPublicKey
. Once you've done that you can access the methods of these classes.
RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic());
BigInteger modulus = pubKey.getModulus();
etc.
Have you looked into the docs?
Try the following :
getModulus
getPublicExponent
getPrivateExponent
They all return BigInteger
than can in turn be stored.
Also see if the raw encoded format is of help.