Generating JWK Thumbprints with Ruby

As mentioned in How are Open Banking Key Ids (kid) Generated?, Open Banking use the JWK thumbprints as defined by RFC7638: JSON Web Key (JWK) Thumbprint.

But these may be used in other circumstances, so it's worth knowing how to generate them. Instead of hand-rolling the generation process, we can re-use the excellent json-jwt:

#!/usr/bin/env ruby
require 'json/jwt'

def read_key(fname)
  contents = File.read fname

  begin
    return OpenSSL::X509::Certificate.new(contents).public_key
  rescue
    # ignore
  end

  begin
    return OpenSSL::PKey.read contents
  rescue
    # ignore
  end

  raise "#{fname} could not be parsed as a certificate, public or private key"
end

hash = ARGV[1] || 'sha256'

key = read_key(ARGV[0])
key = key.public_key unless key.public?

jwk = JSON::JWK.new(key)
puts jwk.thumbprint(hash)

This allows us to run the following:

ruby thumb.rb path/to/private.pem      # works with private key or public key
ruby thumb.rb path/to/public.cer       # works with certificates
ruby thumb.rb path/to/public.pem       # to use default hash algorithm
ruby thumb.rb path/to/public.pem SHA-1 # to specify our own

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #ruby #jwk.

This post was filed under articles.

Has this content helped you? Please consider supporting me so I can continue to create content like this!

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.