-
-
Save invalidred/737ecc593f19468a74ce47d521cb303f to your computer and use it in GitHub Desktop.
Generate private and public keys, and create JWT and JWKs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
## Requires openssl, nodejs, jq | |
header=' | |
{ | |
"kid": "12345", | |
"alg": "RS256" | |
}' | |
payload=' | |
{ | |
"iss": "https://example.com", | |
"sub": "user-id-123", | |
"aud": "client-app-id-123", | |
"exp": 1735689600, | |
"iat": 1563980400 | |
}' | |
function pack() { | |
# Remove line breaks and spaces | |
echo $1 | sed -e "s/[\r\n]\+//g" | sed -e "s/ //g" | |
} | |
if [ ! -f private-key.pem ]; then | |
# Private and Public keys | |
openssl genrsa 2048 > private-key.pem | |
openssl rsa -in private-key.pem -pubout -out public-key.pem | |
fi | |
# Base64 Encoding | |
b64_header=$(pack "$header" | openssl enc -e -A -base64) | |
b64_payload=$(pack "$payload" | openssl enc -e -A -base64) | |
signature=$(echo -n $b64_header.$b64_payload | openssl dgst -sha256 -sign private-key.pem | openssl enc -e -A -base64) | |
# Export JWT | |
echo $b64_header.$b64_payload.$signature > jwt.txt | |
# Create JWK from public key | |
if [ ! -d ./node_modules/pem-jwk ]; then | |
# A tool to convert PEM to JWK | |
npm install pem-jwk | |
fi | |
jwk=$(./node_modules/.bin/pem-jwk public-key.pem) | |
# Add additional fields | |
jwk=$(echo '{"use":"sig"}' $jwk $header | jq -cs add) | |
# Export JWK | |
echo '{"keys":['$jwk']}'| jq . > jwks.json | |
echo "--- JWT ---" | |
cat jwt.txt | |
echo -e "\n--- JWK ---" | |
jq . jwks.json |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment