6

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.

Rodrigue
  • 3,617
  • 2
  • 37
  • 49
ask
  • 149
  • 1
  • 8
  • You need to generate a KeyPair so the PrivateKey can be used to decode the PublicKey. Check out this link https://docs.oracle.com/javase/tutorial/security/apisign/step2.html – mep Mar 24 '18 at 16:30
  • @FattySalami The link you provided gives a method to generate instances of classes PublicKey and PrivateKey but I need instances of the classes RSAPublicKey and RSAPrivateKey. Please see to it. It will be very helpful if you provide a code snippet or some explanation.Thanks. – ask Mar 24 '18 at 16:41

1 Answers1

4

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();
mep
  • 431
  • 1
  • 4
  • 15
  • 3
    That code generares a new keypair. If you want to use an existing keypair, just load it from a keystore (faster) or from a pem file https://stackoverflow.com/questions/11787571/how-to-read-pem-file-to-get-private-and-public-key/14177328 – gusto2 Mar 24 '18 at 19:55