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.
- I followed How to create public and private key with openssl? to generate public and private key.
- I converted private key to the DER form
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out pkcs8.der -nocrypt
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
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.