This example creates a 2048 bits RSA2 key. It is recommended by Alipay that you use a RSA2 key.
require 'openssl'
@app_key = OpenSSL::PKey::RSA.new(2048)
You can save your private and public key as any of two formats. As long as it can be loaded into the program.
Saving Private Key to String
app_private_key = @app_key.to_s
Saving Private Key to File
open 'private_key.pem', 'w' do |io| io.write @app_key.to_pem end
Saving Public Key to String
app_public_key = @app_key.public_key.to_s
Saving Public Key to File
open 'public_key.pem', 'w' do |io| io.write @app_key.public_key.to_pem end
You will need to submit the application public key that you just created to Alipay. However, you will need to strip the header, footer, and new line characters from the key and just submit the key content to Alipay.
key_content = app_public_key.gsub(/(-----BEGIN PUBLIC KEY-----)|(-----END PUBLIC KEY-----)|(\n)/, "")
puts key_content
# => 'MII0ey6QDZLB69i0e5Q0....'
After you submit your application's public key to Alipay. There is an optional step to validate the public key that you just uploaded by signing a parameter provided by Alipay.
# validate params "a=123"
Base64.strict_encode64(@app_key.sign('sha256', "a=123"))
# => 'FokDu5uwgmNG2O/cb0QYD....'
The public key from Alipay does not contain any formatting. Ruby's OpenSSL library cannot import/read the public key without proper formatting. To add formatting back, run the following script.
pub_key = "MIIBI...HpwIDAQAB"
pub_key.scan(/.{64}|.+$/).join("\n").insert(0, "-----BEGIN PUBLIC KEY-----\n").insert(-1, "\n-----END PUBLIC KEY-----\n")
# => "-----BEGIN PUBLIC KEY-----\nMIIBI...\n-----END PUBLIC KEY-----\n"