How to use openssl to generate a JWT using ES256 alogrithm

I am facing difficulty in signing JWT using OPENSSL with ES256 algorithm. Would be great if anyone can share a command or the arguments that needs to be passed to OPENSSL.

I am using the below which is generating an invalid token.

echo -n "eyJhbGciOiJFUzI1NiIsInRUUhLTDkifQ.eyJpc3MiOiI2ZGU3Ni02YTYxLTQ3ZTMtZTA1My01YjhjN2MxMWE0ZDEiLCJleHAiOj1ZCI6ImFwcHN0b3JlY29ubmVjdC12MSIsImlhdCI6MTYzMDk5NzcxMX0" | openssl dgst -sha256 -binary -sign AuthKey_Q8KL9.pem | openssl enc -base64 | tr -d '\n=' | tr -- '+/' '-_'

Would be great, if someone can throw light on the above.

Upvotes: 2

Views: 5282

Answers (2)

Vũ Huy
Vũ Huy

Reputation: 31

I have same problem and found the solution here https://github.com/madaster97/openssl-jws.

he resolve a problem with r || s as filip-skokan have explained by regex

short answer :

$(echo -n "$Y" | openssl dgst -sha256 -sign "$key_path" | openssl asn1parse -inform DER | perl -n -e'/INTEGER           :([0-9A-Z]*)$/ && print $1' | xxd -p -r | base64| tr -d '\n=' | tr -- '+/' '-_' )"

Upvotes: 3

user9775882
user9775882

Reputation:

  1. the filename of your key suggests it is a secp256k1 key, such key is invalid for use for the ES256 JWS Algorithm. The only usable keys for ES256 is P-256 (also known as secp256r1, or prime256v1). The JWS Algorithm name for secp256k1 is ES256K as defined in RFC 8812
  2. assuming you pipe the serialized JWS Protected Header and JWS Payload concattenated by a . then your command may at best produce the JWS Signature, but not the whole token - i'm assuming that's clear
  3. What stands in your way is that OpenSSL generates the ECDSA signatures as DER-encoded ASN.1 structure, rather than a simple r || s as proposed by IEEE-P1363 which is what JWS uses.

1 and 2 is easy to handle, 3 you cannot achieve with openssl, you need some other command that decodes r and s from the DER signature, simply concatenates them and base64url encodes it.

Upvotes: 3

Related Questions