Skip to content

Instantly share code, notes, and snippets.

@ezekg
Last active September 18, 2020 10:16
Show Gist options
  • Save ezekg/57d1508fc1557236fe5eb8803e0e47af to your computer and use it in GitHub Desktop.
Save ezekg/57d1508fc1557236fe5eb8803e0e47af to your computer and use it in GitHub Desktop.
Example of using pub/priv keys for license generation, so license's can be validated online and offline. Note: each step should be run separately. Requires the great https://stedolan.github.io/jq/ command line tool. Node implementation: https://gist.github.com/ezekg/f021009b4c419f2462f3706a4478f200.
# 1. Generate a public/private keypair
openssl genrsa -out priv.pem 512
openssl rsa -in priv.pem -out pub.pem -outform PEM -pubout
# 2. Verify public/private keys look OK
cat priv.pem pub.pem
# 3. Generate a key with an expiry in 1 year and sign with *private* key (server-side)
#
# Note: the expiry you choose should match your license's policy, so that online
# validations return the same result as offline.
echo -n "{\"expiry\":$(date -v +1y +%s),\"key\":\"$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 12)\"}" \
| openssl rsautl -sign -inkey priv.pem \
| base64
# 4. Create a license resource using our newly generated base64 encoded key
curl -X POST https://api.keygen.sh/v1/accounts/{ACCOUNT}/licenses \
-H 'Content-Type: application/vnd.api+json' \
-H 'Accept: application/vnd.api+json' \
-H 'Authorization: Bearer {TOKEN}' \
-d '{
"data": {
"type": "licenses",
"attributes": {
"key": "{GENERATED_KEY}"
},
"relationships": {
"policy": {
"data": { "type": "policies", "id": "{POLICY}" }
}
}
}
}'
# 5. Get the license's key (should probably send it to our customer around this time)
curl https://api.keygen.sh/v1/accounts/{ACCOUNT}/licenses/{LICENSE} \
-H 'Accept: application/vnd.api+json' \
-H 'Authorization: Bearer {TOKEN}' \
| jq .data.attributes.key
# 6. Validate the license key using our *public* key (client-side)
echo -n "{KEY}" \
| base64 -D \ # Decode base64'd key
| (openssl rsautl -verify -inkey pub.pem -pubin 2>/dev/null || echo '{}')
| jq "(.expiry // -1) > $(date +%s)" # Compare expiry with current epoch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment