auth0 / java-jwt

Java implementation of JSON Web Token (JWT)
MIT License
5.85k stars 922 forks source link

Improving the example for loading the public/private keys #374

Closed vojkny closed 4 years ago

vojkny commented 4 years ago

Description

I am trying to follow the example in README.md:

//HMAC
Algorithm algorithmHS = Algorithm.HMAC256("secret");

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

However getting the key instances is not that simple. After a lot of digging I managed to load at least the private key as follows:

  1. I followed https://stackoverflow.com/questions/44474516/how-to-create-public-and-private-key-with-openssl to generate public and private key.
  2. I converted private key to the DER form openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out pkcs8.der -nocrypt
  3. Now I am able to load the private key as:
val privateKey = readKeyAsBytes("pkcs8.der")
        .run { PKCS8EncodedKeySpec(this) }
        .run { KeyFactory.getInstance("RSA").generatePrivate(this) }
        as RSAPrivateKey
  1. However this doesn't work for generating the public key:
val publicKey = readKeyAsBytes("publickey.crt")
        .run { X509EncodedKeySpec(this) }
        .run { KeyFactory.getInstance("RSA").generatePublic(this) }
        as RSAPublicKey

as it fails with InvalidKeyException: invalid key format. I am not sure whether .getInstnace(RSA) is correct here, but I couldn't make it work with anything else either. I guess the public key is not in the X509 format, but I cannot seem to manage to convert it to it.

It would be great to provide some better example to start with this.

Prerequisites

(note this is not a bug)

Environment

Please provide the following:

Reproduction

(not a bug)

jimmyjames commented 4 years ago

This is related to #214. In that issue you'll find a link to a gist demonstrating how you could obtain the keys. I think updating the README to refer to that gist would help.