Ruby RSA from exponent and modulus strings

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

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.

Tags:

Ruby

Rsa