Techioz Blog

指数文字列とモジュラス文字列からの Ruby RSA

概要

RSA 公開キーの係数と指数文字列を持っています。

これら 2 つの文字列から OpenSSL::PKey::RSA を作成したいと考えています。

基本的には次のようになります。

Ruby でこれを行うにはどうすればよいでしょうか? 最終的な目標は、これを JWT gem に取り込むことです。

私は現在 Ruby 2.3.1 を使用しているので、これは機能します:

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

ただし、アップグレード中は機能しません。

解決策

この Python 実装に基づいて、このように動作させることができました。

https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=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