Created
January 25, 2023 22:28
-
-
Save iamricks/f9f56db450784f7f6d652d6101017d4c to your computer and use it in GitHub Desktop.
Generate a JSON web key set in Ruby from a .pem cert
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
require 'openssl' | |
require 'base64' | |
require 'json' | |
# Open certificate file | |
cert = OpenSSL::X509::Certificate.new(File.read('certificate.pem')) | |
modulus = cert.public_key.n.to_s(2) | |
modulus_b64 = Base64.urlsafe_encode64(modulus, padding: false) | |
# Extract x5c from certificate | |
x5c = cert.to_der | |
x5c_b64 = Base64.urlsafe_encode64(x5c, padding: false) | |
# Extract x5t from certificate | |
x5t = OpenSSL::Digest::SHA1.new(cert.to_der).to_s | |
x5t_b64 = Base64.urlsafe_encode64(x5t, padding: false) | |
# Extract kid from certificate | |
kid = OpenSSL::Digest::SHA1.new(cert.to_der).to_s | |
kid_b64 = Base64.urlsafe_encode64(kid, padding: false) | |
jwk = { keys: [{ | |
alg: "RS256", | |
kty: 'RSA', | |
use: 'sig', | |
n: modulus_b64, | |
e: 'AQAB', | |
x5c: [x5c_b64], | |
x5t: x5t_b64, | |
kid: kid_b64 | |
} | |
]} | |
puts jwk.to_json |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment