Skip to content

Instantly share code, notes, and snippets.

@joostd
Created December 19, 2023 11:26
Show Gist options
  • Save joostd/6a55084a7171214372b7ce3c5dc43dd5 to your computer and use it in GitHub Desktop.
Save joostd/6a55084a7171214372b7ce3c5dc43dd5 to your computer and use it in GitHub Desktop.
Sign a JWT using a key generated on a YubiKey
#!/bin/bash
# step 1 - generate a new key pair on a YubiKey
yubico-piv-tool -a generate -s 9c -A ECCP256 -o pub.pem
# step 2 - generate data to be signed
jo iss=issuer aud=audience > payload.json
jo alg=ES256 typ=JWT > header.json
# base64-encode header and payload
basenc --base64url header.json | tr -d '\n=' > header.b64
basenc --base64url payload.json | tr -d '\n=' > payload.b64
echo -n . > dot
cat header.b64 dot payload.b64 > datatosign
# step 3 - sign using yubikey
yubico-piv-tool -a verify-pin --sign -s 9c -H SHA256 -A ECCP256 -i datatosign -o signature.der
# step 4 - verify
# verify using openssl
openssl dgst -sha256 -verify pub.pem -signature signature.der datatosign
# convert openssl signature
cat signature.der | openssl asn1parse -inform der | egrep -o '[A-F0-9]{64}' | xxd -r -p | basenc --base64url | tr -d '\n=' > signature.b64
# construct jwt
cat datatosign dot signature.b64 > token.jwt
# verify using step
cat token.jwt | step crypto jwt verify --key pub.pem --iss issuer --aud audience
# verify using jwt.io
echo "Open the following URL in your browser:"
echo "https://jwt.io/#debugger-io?token=$(cat token.jwt)&publicKey=$(jq -sRr @uri pub.pem)"
@joostd
Copy link
Author

joostd commented Dec 19, 2023

This script uses a number of command-line tools:

  • yubico-piv-tool for generating keys and signatures using a YubiKey
  • jo to generate JSON files
  • basenc for base64url encoding
  • openssl for converting ECDSA signatures
  • step for validating JWT tokens
  • jq for encoding URLs

On macOS, use brew to install tools not installed by default:

brew install yubico-piv-tool jo coreutils step

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment