5

I'm trying to replicate the following python code in ruby. The python code works fine, the ruby code fails due to "padding check failed". I can encrypt a string and decrypt it with the private key in Ruby, but the encrypted data I need to work with is being retrieved from elsewhere. I'm unsure of the library and even language used to encrypt it, but the Python code works.

Working Python code:

def decrypt_secret(encrypted_base64, private_key):
  key = RSA.importKey(open(private_key, "r").read())
  pkey = PKCS1_OAEP.new(key, hashAlgo=SHA256)
  encrypted_blob = base64.urlsafe_b64decode(encrypted_base64)
  decrypted_string = pkey.decrypt(encrypted_blob)
  return decrypted_string

Ruby Code fails "padding check failed"

def decrypt_secret(encrypted_base64, private_key)
  key = File.read(private_key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted_blob = Base64.urlsafe_decode64(encrypted_base64)
  decrypted_string = pkey.private_decrypt(encrypted_blob, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
  return decrypted_string
end 

2 Answers 2

4

I found the needed functions contained in the JOSE gem to support SHA256 OAEP. The following code does the job:

require 'jose'
def decrypt_secret(encrypted_base64, private_key)
  key = File.read(private_key)
  pkey = OpenSSL::PKey::RSA.new(key)
  encrypted_blob = Base64.urlsafe_decode64(encrypted_base64)
  decrypted_string = JOSE::JWA::PKCS1::rsaes_oaep_decrypt(OpenSSL::Digest::SHA256, encrypted_blob, pkey)
  return decrypted_string
end
Sign up to request clarification or add additional context in comments.

Comments

1

It doesn't look like Ruby's OpenSSL wrapper exposes the option to change the hash function for OAEP. You would need to change the Python code to use SHA-1 (default):

pkey = PKCS1_OAEP.new(key)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.