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
  • 3
  • 8
  • Since this is about how to use a piece of software, it appears to be more on-topic for a site like superuser rather than crypto.stackexchange. I can migrate this there for you. –  Mar 29 '19 at 19:00
  • 3
    `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](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo) – dave_thompson_085 Mar 30 '19 at 00:43
  • Right, it was indeed the newline. Thanks! Mind adding a reply so I can accept it? – fstanis Mar 31 '19 at 23:32

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
  • 3
  • 8