Skip to content

Instantly share code, notes, and snippets.

@maraino
Created January 13, 2023 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraino/f73b334e475caa1a0f34a52c501fede7 to your computer and use it in GitHub Desktop.
Save maraino/f73b334e475caa1a0f34a52c501fede7 to your computer and use it in GitHub Desktop.
JWT tokens with an HSM
#!/bin/bash
set -e
KMS="pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;token=smallstep?pin-value=password"
KEY="pkcs11:id=2001"
ALG="ES256"
KID=$(step kms key --kms "${KMS}" "${KEY}" | step crypto key format --jwk | step crypto jwk thumbprint)
AUD="https://ca.smallstep.com:9000/1.0/sign"
SUB="localhost"
SHA="a78a850025c0c234385eda23d7192964ca56aa9d727f535653b0afb81c1e0559"
ISS="mariano@smallstep.com"
EXP=$(date -v+5M +"%s")
IAT=$(date +"%s")
JTI=$(cat /dev/urandom | head -c 32 | xxd -ps -cols 0)
HEADER='{
"alg":"'${ALG}'",
"kid":"'${KID}'",
"typ": "JWT"
}'
PAYLOAD='{
"aud": "'${AUD}'",
"exp": '${EXP}',
"iat": '${IAT}',
"iss": "'${ISS}'",
"jti": "'${JTI}'",
"nbf": '${IAT}',
"sans": ["'${SUB}'"],
"sha": "'${SHA}'",
"sub": "'${SUB}'"
}'
DATA=$(echo -n $HEADER | jq -c | tr -d '\n' | step base64 -u -r).$(echo -n $PAYLOAD | jq -c | tr -d '\n' | step base64 -u -r)
SIG=$(step kms sign --format jws --in <(echo -n ${DATA}) --kms "${KMS}" "${KEY}")
echo $DATA.$SIG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment