0

I am trying to use the simple example given here:

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

//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);

Unfortunately getting the key instances for public and private key is not that simple.

  1. I followed 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
    
  4. 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.

Vojtěch
  • 11,312
  • 31
  • 103
  • 173

1 Answers1

0

You say that you converted the private key file 'private_key.pem', to a DER format, but did you also convert the public key to a DER format.

The readKeyAsBytes function is expecting binary data.

DER stands for Distinguished encoding rules; it is a binary format. PEM is just a base64 encoded representation of the DER binary data with a header before and a footer after. But it is ascii text not binary.

If you open the files with a text editor, the DER file will be a bunch of crazy unreadable stuff.

The PEM files will look something like this:

-----BEGIN CERTIFICATE----- 
MIIGuzCCBaOgAwIBAgIUT2q/veSq2N3hq+1QSqfrZo6SW8IwDQYJKoZIhvcNAQEL 
...
Wu/svFTqcFBje8FiO98kFwJwSuajwt9l2mToy7W7PkQ+WARIOLR/7pcNh27O99Y=
-----END CERTIFICATE-----

Good luck

Mark Arnott
  • 1,975
  • 3
  • 17
  • 28