简体   繁体   中英

Ruby/Rails OpenSSL::PKey::RSAError: data greater than mod len

I think I started getting this error when I switched from MySQL to PostgreSQL. I had written code to encrypt decrypt model attributes containing sensitive data and I had it working until the db switch.

I have the following code:

@pbk = OpenSSL::PKey::RSA.new File.read("#{RAILS_ROOT}/cert/pb_sandwich.pem")
@pvk = OpenSSL::PKey::RSA.new File.read("#{RAILS_ROOT}/cert/tuna_salad.pem"), 'pass45*'
model.sendata = Base64.encode64 @pbk.public_encrypt(model.sendata)

I run that code on save. I've also tried with and with out first using Base64.

Then when I try to read:

@pvk.private_decrypt Base64.decode64(model.sendata)

I get this error:

OpenSSL::PKey::RSAError: data greater than mod len

I never got that before when I used MySQL. I can't really remember what datatype the sendata column was in MySQL but in my current PostgreSQL setup that column is datatype bytea

I'm assuming that is the problem since it used to work fine with MySQL. What datatype should the column be if I wanted to skip having to do that extra step to Base64 encode/decode? If that is the problem that is.

Another thing of note is that I've tried generating the private key with mod lengths: 2048, 4096, and 5120 and I always get the same error. Also, the sendata field isn't very long before encoding, it's under 40 chars.

I'm stumped right now, any ideas?

You are probably not storing the keys properly in the Database. There's probably some field that is being truncated.

The message you are getting probably means that the data is too long to be encrypted with such a small key. If this is the case, you should encrypt the data with AES and encrypt the AES key with RSA. Then send both the encryted data and the encrypted key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM