如何在 ruby​​ on Rails 中将字符串转换为字节数组

Bec*_*cka 4 ruby-on-rails

我想先将字符串转换为字节数组,然后才能使用私钥对其进行签名,但我以前没有这样做过。我的代码如下所示,任何人都可以告诉我如何做到这一点。谢谢。

require 'openssl'
require 'base64'
require 'digest/sha1'

@date = Date.today.strftime("%m/%d/%Y")
text_to_sign = "#{@order.phone_no}" + "#{@order.name}" + "#{@order.pay_type}" + "#{@order.pay_type}" + "1" + "MABIRA" + "81W30DI846" + "#{@date}" + "PULL" + "1" + "#{@cart.total_price}" + "#{@order.phone_no}" + ""
password = 'secret'

#converting the string to byte array
byte[] buff => new byte[1024]
text = buff.text_to_sign


private_key = OpenSSL::PKey::RSA.new(File.read('Private.key'), password)
ciphertext = private_key.private_encrypt(text)
ciphertext.encoding
signed_text = Base64.encode64(ciphertext).gsub("\n", '')
puts signed_text
signed_text
Run Code Online (Sandbox Code Playgroud)

Eye*_*dic 6

Ruby 有该方法,您可以使用http://www.ruby-doc.org/core-1.9.3/ARGF.html#method-i-bytesbytes将其转换为数组to_a

string = 'some string'
byte_array = string.bytes.to_a
# [115, 111, 109, 101, 32, 115, 116, 114, 105, 110, 103] 
Run Code Online (Sandbox Code Playgroud)