You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby基础RSA公私钥示例解密报错:data greater than mod len

解决RSA解密时的data greater than mod len错误

嘿,我帮你定位到问题啦!这个错误的根源在于你没有对Base64编码后的加密字符串做解码,就直接传给了private_decrypt方法。

错误原因详解

Base64.encode64方法会生成带有换行符的输出(默认每60个字符就换行)。当你直接把这个带换行的字符串传给private_decrypt时,OpenSSL会把这些换行符也当作加密数据的一部分处理,导致数据总长度超过了RSA密钥的模数长度,最终抛出data greater than mod len的错误。

修正后的代码

只需要在解密前,先用Base64.decode64把编码后的字符串还原成原始的加密二进制数据即可:

require 'openssl'
require 'base64'

key = OpenSSL::PKey::RSA.generate(2048)
pri_key = key
pub_key = key.public_key

string = 'Hello World!'
# 这里可以直接用pub_key,无需重新实例化
encrypted_data = pub_key.public_encrypt(string)
encrypted_string = Base64.encode64(encrypted_data)

puts "Encrypted Message:"
puts encrypted_string

# 关键修正步骤:先解码Base64字符串
decoded_encrypted_data = Base64.decode64(encrypted_string)
my_string = pri_key.private_decrypt(decoded_encrypted_data)

puts "The decoded message"
puts my_string

额外优化提示

代码里的rsa_public_key = OpenSSL::PKey::RSA.new(pub_key)其实是多余的,因为pub_key本身就是OpenSSL::PKey::RSA的实例,直接调用pub_key.public_encrypt(string)就可以完成加密,这样能让代码更简洁。

内容的提问来源于stack exchange,提问作者Adjam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:43:06