8

I'm trying to sign a JWT token with the RS256 algorithm using openssl. Take the following example token:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

Per RFC 7518, RS256 means the signature used is "RSASSA-PKCS1-v1_5 using SHA-256". My understanding is that the following use of openssl dgst would do:

# generate the key
openssl genrsa -out private.pem 2048

generate the signature

echo 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ' |
openssl dgst -sha256 -sign private.pem -binary |
openssl base64 |
tr -- '+/=' '-_ '

However, trying to use jwt.io to verify results in invalid signature. Furthermore, using jwt.io to generate a signature using the same private key produces a completely different one.

What am I doing wrong? Is openssl dgst the correct way to sign this token?

fstanis
  • 358

1 Answers1

0

echo echoes its argument(s) as a line -- meaning it adds a newline character. On some systems or shells -n suppresses this, but printf '%s' 'string' is reliably correct.

# generate the key
openssl genrsa -out private.pem 2048

generate the signature

printf '%s' 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ' |
openssl dgst -sha256 -sign private.pem -binary |
openssl base64 |
tr -- '+/=' '-_ '

fstanis
  • 358