在Ruby / Rails中,如何解密由PKCS7加密和签名的字符串

在PayPal上的这个RailsCast中,它向您展示了如何在将URL参数发送到PayPal之前对其进行加密。

PAYPAL_CERT_PEM = File.read("#{Rails.root}/certs/paypal_cert.pem") APP_CERT_PEM = File.read("#{Rails.root}/certs/app_cert.pem") APP_KEY_PEM = File.read("#{Rails.root}/certs/app_key.pem") def encrypt_for_paypal(values) signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM), OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''), values.map { |k, v| "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY) OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)], signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"), OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "") end 

假设我正在为PayPal的服务器编写代码。 我该如何解密这个字符串? 在我看来,这个代码公钥都签署了字符串(以validation真实性),然后加密字符串(以提供隐私)。 代码用于反向,解密和validation真实性是什么?

谢谢。

嗨John这里是使用ruby openssl加密/解密的一个例子。 注意它使用AES作为密码,因为DES3似乎在我的ruby openssl版本中被删除了。 在字符串上调用gsub来替换换行符似乎打破了它,所以我把它留下了注释掉。 希望它可以帮助你。

 require 'openssl' PAYPAL_CERT_PEM = File.read("paypal_cert.pem") @paypal_cert = OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM) APP_CERT_PEM = File.read("app_cert.pem") @app_cert = OpenSSL::X509::Certificate.new(APP_CERT_PEM) APP_KEY_PEM = File.read("app_key.pem") @app_key = OpenSSL::PKey::RSA.new(APP_KEY_PEM, '') PAYPAL_KEY_PEM = File.read("paypal_key.pem") @paypal_key = OpenSSL::PKey::RSA.new(PAYPAL_KEY_PEM, '') CERT_STORE = OpenSSL::X509::Store.new CERT_STORE.add_cert(@app_cert) data = Hash.new data['customer_id'] = '123456789' data['customer_name'] = 'Mr Smith' def encrypt_for_paypal(values) data_name_values = values.map { |k, v| "#{k}=#{v}" } signed_data = OpenSSL::PKCS7::sign(@app_cert, @app_key, data_name_values.join("\n"), [], OpenSSL::PKCS7::BINARY) cypher = OpenSSL::Cipher::new("AES-128-CFB") encrypted_data = OpenSSL::PKCS7::encrypt([@paypal_cert], signed_data.to_der, cypher, OpenSSL::PKCS7::BINARY) encrypted_data.to_s #.gsub("\n", "") end def decrypt_by_paypal(encrypted_data) received_encrypted_data = OpenSSL::PKCS7.new(encrypted_data) received_signed_data = received_encrypted_data.decrypt(@paypal_key, @paypal_cert) p7_received_signed_data = OpenSSL::PKCS7.new(received_signed_data) p7_received_signed_data.verify(nil, CERT_STORE, nil, OpenSSL::PKCS7::NOVERIFY) p7_received_signed_data.data end encrypted_txt = encrypt_for_paypal data puts decrypt_by_paypal encrypted_txt 
Interesting Posts