Skip to content

Instantly share code, notes, and snippets.

@iDanielLaw
Forked from timmc/jwt-sign-ES256.sh
Created June 15, 2019 09:13
Show Gist options
  • Save iDanielLaw/b39d58564274fa9a75a92654e1475748 to your computer and use it in GitHub Desktop.
Save iDanielLaw/b39d58564274fa9a75a92654e1475748 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Create and sign a JWT token with ES256 given the path to an ECDSA
# private key and a JSON payload.
# $0 path/to/keypair.der '{"JSON": "payload"}'
# Example keypair creation:
# openssl ecparam -name prime256v1 -genkey -noout -outform DER > example-keypair.der
# A few tips for generating the payload:
# - Pipe raw strings through `jq --raw-input .` to encode them as
# JSON strings. https://stedolan.github.io/jq/
# - GNU date is great for generating the iat, nbf, and exp time
# fields: `date --date="15 minutes" +"%s"`
set -eu -o pipefail
keypair_path="$1"
payload="$2"
function base64_urlsafe {
# Implement own URL-safe Base64 based on standard version. Delete
# padding, undo wrapping, and swap out chars 62 and 63. Not all
# versions of `base64` have the `--wrap=0` that GNU coreutils has.
base64 | tr -d '\r\n=' | tr '+/' '-_'
}
header_enc="$(echo -n '{"typ":"JWT","alg":"ES256"}' | base64_urlsafe)"
payload_enc="$(echo -n "$payload" | base64_urlsafe)"
message="$header_enc.$payload_enc"
# If you're on a Mac, you might have a really old version of openssl
# that doesn't support ECDSA signing this way.
sig="$(echo -n "$message" | openssl dgst -sha256 -sign "$keypair_path" -keyform DER | base64_urlsafe)"
echo -n "$message.$sig"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment