Created
March 5, 2025 07:28
Script for generating a public/private key pair
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/bash | |
# Generate private key in PEM format | |
openssl genpkey -algorithm RSA -out private.key.pem -pkeyopt rsa_keygen_bits:2048 | |
# Generate public key in PEM format (intermediate step) | |
openssl rsa -pubout -in private.key.pem -out public.key.pem | |
# Convert private key to JWK (JSON Web Key) format | |
private_jwk=$(openssl rsa -in private.key.pem -noout -text | \ | |
awk ' | |
/modulus:/{p=1;next}/publicExponent:/{p=0}p' | \ | |
tr -d ' \n:' | \ | |
xxd -r -p | base64 -w 0 | \ | |
tr '+/' '-_' | tr -d '=') | |
private_exp=$(openssl rsa -in private.key.pem -noout -text | \ | |
awk '/privateExponent:/{p=1;next}/prime1:/{p=0}p' | \ | |
tr -d ' \n:' | \ | |
xxd -r -p | base64 -w 0 | \ | |
tr '+/' '-_' | tr -d '=') | |
# Convert public key to JWK format | |
modulus=$(openssl rsa -pubin -in public.key.pem -modulus -noout | \ | |
cut -d'=' -f2 | \ | |
xxd -r -p | base64 -w 0 | \ | |
tr '+/' '-_' | tr -d '=') | |
# Generate key ID (kid) | |
kid=$(openssl rand -hex 32) | |
# Create public key JWK | |
echo "{ | |
\"kty\": \"RSA\", | |
\"kid\": \"$kid\", | |
\"n\": \"$modulus\", | |
\"e\": \"AQAB\", | |
\"alg\": \"RS256\", | |
\"use\": \"sig\" | |
}" > public.key.json | |
# Create private key JWK | |
echo "{ | |
\"kty\": \"RSA\", | |
\"kid\": \"$kid\", | |
\"n\": \"$modulus\", | |
\"e\": \"AQAB\", | |
\"d\": \"$private_exp\", | |
\"alg\": \"RS256\", | |
\"use\": \"sig\" | |
}" > private.key.json | |
echo "Keys generated successfully!" | |
echo "Files created:" | |
echo "- private.key.pem (Private key in PEM format)" | |
echo "- private.key.json (Private key in JWK format)" | |
echo "- public.key.json (Public key in JWK format)" | |
# Display the generated kid for reference | |
echo -e "\nKey ID (kid) for reference:" | |
echo "$kid" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment