Ruby加密文本如何在Python服务端正确解密?
Ruby加密文本在Python端解密的正确方案
问题根源在于Ruby与Python默认使用的RSA填充模式不匹配:Ruby的public_encrypt默认采用PKCS#1 v1.5填充,而Python提示使用的PKCS1_OAEP是另一种更安全的填充模式,两者不兼容导致解密失败。需保持两端填充模式一致,以下是两种可行方案:
方案1:改用PKCS#1 OAEP加密解密(推荐,安全性更高)
Ruby端修改加密代码(指定OAEP填充)
require "base64" require "openssl" public_key = OpenSSL::PKey::RSA.new File.read './publickey.pem' # 指定PKCS#1 OAEP填充,默认哈希算法为SHA1,与Python端保持一致 encrypted = public_key.public_encrypt( "Hello everyone. This is a secret phrase.", OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING ) uri = URI('#...') params = { "passage" => Base64.encode64(encrypted) } response = HTTParty.post( uri, :body => params.to_json, :headers => {'Content-Type' => 'application/json'} )
Python端解密代码(使用PKCS1_OAEP)
from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA import base64 f = open('./privatekey.pem', 'rb') private_key = RSA.importKey(f.read()) f.close() # 初始化OAEP解密器,默认哈希算法SHA1与Ruby端匹配 cipher = PKCS1_OAEP.new(private_key) # 先对Base64编码的密文解码,再解密 decrypted_data = cipher.decrypt(base64.b64decode(encrypted)) return decrypted_data.decode('utf-8')
方案2:兼容原有Ruby代码,Python用PKCS#1 v1.5解密
如果无法修改Ruby端代码,Python端需使用对应v1.5填充的解密模块:
from Crypto.Cipher import PKCS1_v1_5 from Crypto.PublicKey import RSA import base64 f = open('./privatekey.pem', 'rb') private_key = RSA.importKey(f.read()) f.close() # 初始化v1.5解密器 cipher = PKCS1_v1_5.new(private_key) # 解码Base64密文 encrypted_data = base64.b64decode(encrypted) # 执行解密,第二个参数设为None即可 decrypted_data = cipher.decrypt(encrypted_data, None) return decrypted_data.decode('utf-8')
注意事项
- 两端必须保持填充模式、哈希算法完全一致;若需更换SHA256等哈希算法,需在Ruby和Python代码中同时指定。
- RSA仅适合加密短文本(2048位密钥下,v1.5最多支持245字节,OAEP最多支持214字节),长文本建议采用「对称加密(如AES)+ RSA加密对称密钥」的组合方案。
内容的提问来源于stack exchange,提问作者user3574603
相关产品推荐
相关产品推荐

