Skip to content

Instantly share code, notes, and snippets.

@trojkac
Last active October 31, 2023 02:07
Show Gist options
  • Save trojkac/a78d5af6c62cc743dad6fbd7e337701b to your computer and use it in GitHub Desktop.
Save trojkac/a78d5af6c62cc743dad6fbd7e337701b to your computer and use it in GitHub Desktop.
Getting OpenSSL::PKey::RSA from base64 encoded modulus and exponent in JSON Web Key format
e = "AQAB"
n = "lxrwmuYSAsTfn-lUu4goZSXBD9ackM9OJuwUVQHmbZo6GW4Fu_auUdN5zI7Y1dEDfgt7m7QXWbHuMD01HLnD4eRtY-RNwCWdjNfEaY_esUPY3OVMrNDI15Ns13xspWS3q-13kdGv9jHI28P87RvMpjz_JCpQ5IM44oSyRnYtVJO-320SB8E2Bw92pmrenbp67KRUzTEVfGU4-obP5RZ09OxvCr1io4KJvEOjDJuuoClF66AT72WymtoMdwzUmhINjR0XSqK6H0MdWsjw7ysyd_JhmqX5CAaT9Pgi0J8lU_pcl215oANqjy7Ob-VMhug9eGyxAWVfu_1u6QJKePlE-w"
decoded_exponent = Base64.urlsafe_decode64(e)
decoded_modulus = Base64.urlsafe_decode64(n)
e = OpenSSL::BN.new(decoded_exponent, 2)
n = OpenSSL::BN.new(decoded_modulus, 2)
OpenSSL::PKey::RSA.new.set_key(n, e, nil)
@ayqazi
Copy link

ayqazi commented Aug 1, 2023

For anyone coming here from the web, on Ruby 3.2 this gives:

rsa#set_key= is incompatible with OpenSSL 3.0 (OpenSSL::PKey::PKeyError)

@hugochougt
Copy link

The gist below can solve "rsa#set_key= is incompatible with OpenSSL 3.0 (OpenSSL::PKey::PKeyError)" problem:

ruby_rsa_publickey.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment