Creating Signed JOSE Objects with Ruby

Featured image for sharing metadata for article

I've written before about how to create a Signed JWT with Ruby.

But sometimes you don't want a JSON Web Token (JWT). You actually just want to create a JSON Object Signing and Encryption (JOSE) object. This could be that you want to try and create JWT-like formats, but with invalid fields, or you just want to sign arbitrary objects.

We'll create a new command-line tool which allows a file of content to be signed:

ruby sign.rb content.txt 'hmac-key-here'
ruby sign.rb payload.json 'hmac-key-here'
ruby sign.rb payload.json 'hmac-key-here' 'HS256'
ruby sign.rb payload.json '/path/to/key.pem' 'RS256'
ruby sign.rb payload.json '/path/to/key.pem' 'ES256'

We can utilise the great ruby-jose library to sign an arbitrary payload of data to provide the following script:

require 'jose'

def read_key(maybe_secret)
  if File.exists? maybe_secret
    JOSE::JWK.from_pem_file maybe_secret
  else
    JOSE::JWK.from_oct maybe_secret
  end
end

payload = File.read ARGV[0]
jwk = read_key(ARGV[1])
algorithm = ARGV[2] || 'HS256'

options = {
  'alg' => algorithm,
}

puts jwk.sign(payload, options).compact

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 #command-line #jwt #jose.

This post was filed under articles.

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.