ask
ask

Reputation: 151

How to use RSAPublicKey and RSAPrivateKey classes in Java?

I am trying to use [Java JWT] library(https://github.com/auth0/java-jwt) to generate JWT and I require to make instances of private key and public key i.e. RSAPrivateKey and RSAPublicKey.

//RSA
RSAPublicKey publicKey = //Get the key instance
RSAPrivateKey privateKey = //Get the key instance
Algorithm algorithmRS = Algorithm.RSA256(publicKey, privateKey);

How do I create the instances of RSAPrivateKey and RSAPublicKey?

I have created .pem files using OpenSSL (if that helps) but I am not able to use that too.

Upvotes: 6

Views: 9635

Answers (1)

mep
mep

Reputation: 491

First create the KeyPairGenerator to create the KeyPairs.

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");

This will give you a KeyPairGenerator using RSA. Next you initialize the generator with the amount of bytes you want it to use and then create the KeyPair.

kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();

Get the PublicKey and PrivateKey from the KeyPair kp using their Getters and than because RsaPublicKey is just a a SubClass of Key and we made these keys with RSA we can safely cast the PublicKey and PrivateKey classes to RSAPublicKey and RSAPrivateKey

RSAPublicKey rPubKey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey rPriKey = (RSAPrivateKey) kp.getPrivate();

Upvotes: 7

Related Questions