invalid key format in JWT

1,185 views
Skip to first unread message

Konstantin Smirnov

unread,
Jul 23, 2020, 7:49:54 AM7/23/20
to vert.x

Hi all,

I created a pub/priv cert pair with:

.\openssl.exe genpkey -algorithm RSA -out ../ca_private.pem -pkeyopt rsa_keygen_bits:2048
.\openssl.exe req -x509 -new -nodes -key ..\ca_private.pem -sha256 -out ..\ca_cert.pem -subj "/CN=unused" -config .\openssl.cnf -days 7300


With those 2 files I'm trying to instantiate a JWT:

    import static java.nio.charset.StandardCharsets.ISO_8859_1

    JWT jwt = new JWT()
    String pubKey = new String( getClass().getResourceAsStream( '/ca_cert.pem' ).bytes, ISO_8859_1 )
    String privKey = new String( getClass().getResource( '/ca_private.pem' ).bytes, ISO_8859_1 )
    jwt.addJWK new JWK( 'RS256', true, pubKey, privKey )

The code is throwing the exception:

java.lang.RuntimeException: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at io.vertx.ext.jwt.JWK.<init>(JWK.java:139)
    .....
Caused by: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
    at io.vertx.ext.jwt.JWK.<init>(JWK.java:131)
    ... 43 more
Caused by: java.security.InvalidKeyException: invalid key format
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:331)
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
    at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)

What am I missing?

Paulo Lopes

unread,
Jul 27, 2020, 8:03:50 AM7/27/20
to vert.x
Hi,

The JDK itself only support PKCS8 keys, so after you create your keys with openssl you need one extra step:

openssl pkcs8 -topk8 -inform PEM -in private.pem -out private_key.pem -nocrypt

This converts the "private.pem" file to pk8 formar as "private_key.pem".

You should do this to both public and private pem files.

Konstantin Smirnov

unread,
Jul 27, 2020, 9:32:19 AM7/27/20
to vert.x
Thanks for reply.

I ran the command, but the PCKS8 file generated is the same, as the the original one...
Reply all
Reply to author
Forward
0 new messages