5

https://github.com/auth0/java-jwt

States that setting up the algorithm for JWT should be as simple as

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

The problem is I can't work out how to create an RSAPublicKey and RSAPrivateKey instance without touching the filesystem.

  1. It should be secure.
  2. It shouldn't create the key on the file system, as I plan on storing it via another method.

Normally this is the sort of thing I'd guess at until I get right, but considering it's cryptography I want to do the right thing.

keygen = KeyPairGenerator.getInstance("RSA");
        RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4); //What does F4 mean vs F0?
            keygen.initialize(spec);
            KeyPair keypair = keygen.generateKeyPair();
            PublicKey pub = keypair.getPublic(); //Wrong type, need RSAPublicKey
            PrivateKey priv = keypair.getPrivate(); //Wrong type, need RSAPrivateKey
Ryan Leach
  • 4,262
  • 5
  • 34
  • 71

1 Answers1

4

You can directly cast the public and private keys to RSAPublicKey and RSAPrivateKey because you are using a RSA KeyPairGenerator

RSAPublicKey rsaPublicKey = (RSAPublicKey) keypair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keypair.getPrivate();

You can get the key content using key.getEncoded(); (no cast needed) and store it as a byte array any way you like

pedrofb
  • 37,271
  • 5
  • 94
  • 142
  • Do you know what the F0 vs F4 exponents are for? – Ryan Leach Oct 16 '17 at 08:18
  • I think F0 (3) is the minimum value for public exponent used by `RSAKeyPairGenerator` and F4(65537) is the recommended value by RFC. See https://crypto.stackexchange.com/questions/3110/impacts-of-not-using-rsa-exponent-of-65537 – pedrofb Oct 16 '17 at 08:24