Skip to content

Instantly share code, notes, and snippets.

@iamricks
Created January 25, 2023 22:28
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 iamricks/f9f56db450784f7f6d652d6101017d4c to your computer and use it in GitHub Desktop.
Save iamricks/f9f56db450784f7f6d652d6101017d4c to your computer and use it in GitHub Desktop.
Generate a JSON web key set in Ruby from a .pem cert
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