Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby RSA from exponent and modulus strings

Tags:

ruby

rsa

I have an RSA public key modulus and exponent string.

I want to create a OpenSSL::PKey::RSA from these two strings.

Basically they come in as:

  • n = 'long string'
  • e = '4-character string'

How would I do this in Ruby? The end goal is to get this to the JWT gem.

Update

I'm currently in Ruby 2.3.1, so this works:

key = OpenSSL::PKey::RSA.new
key.e = OpenSSL::BN.new(Base64.decode64(e), 2)
key.n = OpenSSL::BN.new(Base64.decode64(n), 2)

However, it won't work during an upgrade.

like image 779
el n00b Avatar asked Sep 08 '17 16:09

el n00b


3 Answers

I got it working this way, based on this python implementation:

https://github.com/jpf/okta-jwks-to-pem/blob/master/jwks_to_pem.py

    key = OpenSSL::PKey::RSA.new
    exponent = kid_header['e']
    modulus = kid_header['n']


    # Voila !
    key.set_key(base64_to_long(modulus), base64_to_long(exponent), nil)

    def base64_to_long(data)
      decoded_with_padding = Base64.urlsafe_decode64(data) + Base64.decode64('==')
      decoded_with_padding.to_s.unpack('C*').map do |byte|
        to_hex(byte)
      end.join.to_i(16)
    end

    def to_hex(int)
      int < 16 ? '0' + int.to_s(16) : int.to_s(16)
    end
like image 148
ronnie bermejo Avatar answered Oct 25 '22 16:10

ronnie bermejo


For Ruby 2.4+ you should use :

key = OpenSSL::PKey::RSA.new
key.set_key(n, e, d)

if you do not have d you can set it to nil.

like image 34
OmG3r Avatar answered Oct 25 '22 14:10

OmG3r


You can use JSON::JWT gem (https://rubygems.org/gems/json-jwt, https://github.com/nov/json-jwt)

# can be found somewhere in `.well-known` space on the server
key_hash = {
  "kty": "RSA",
  "use": "sig",
  "kid": ...,
  "e": ...,
  "n": ...,
  "alg": "RS256"
}
jwk = JSON::JWK.new(key_hash)
JSON::JWT.decode token, jwk.to_key
# voila!

The same can be achieved with Ruby JWT (https://rubygems.org/gems/jwt, https://github.com/jwt/ruby-jwt/blob/master/lib/jwt/jwk/rsa.rb)

public_key = JWT::JWK::RSA.import(key_hash).public_key
JWT.decode token, public_key, true, { algorithm: key_hash[:alg] }
like image 20
januszm Avatar answered Oct 25 '22 15:10

januszm