ruby-on-rails 在Ruby中使用HMAC SHA256

jxct1oxe  于 2023-01-03  发布在  Ruby
关注(0)|答案(4)|浏览(208)

我正在尝试应用HMAC-SHA 256为Rest API生成密钥。
我在做这样的事情:

def generateTransactionHash(stringToHash)
  key = '123'
  data = 'stringToHash'
  digest = OpenSSL::Digest.new('sha256')

  hmac = OpenSSL::HMAC.digest(digest, key, data)
  puts hmac
end

其输出始终为:(如果我把'12345'作为参数或'HUSYED 815 X',我得到的是相同的)

ۯw/{o���p�T����:��a�h��E|q

API不工作,因为这个...有人能帮我吗?

kcugc4gi

kcugc4gi1#

根据文件OpenSSL::HMAC.digest
返回示例表示为二进制字符串的身份验证代码。
如果在使用时遇到问题,可能需要OpenSSL::HMAC.hexdigest提供的十六进制编码形式
示例

key = 'key'
data = 'The quick brown fox jumps over the lazy dog'
digest = OpenSSL::Digest.new('sha256')

OpenSSL::HMAC.digest(digest, key, data)
#=> "\xF7\xBC\x83\xF40S\x84$\xB12\x98\xE6\xAAo\xB1C\xEFMY\xA1IF\x17Y\x97G\x9D\xBC-\x1A<\xD8"

OpenSSL::HMAC.hexdigest(digest, key, data)
#=> "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
7gcisfzg

7gcisfzg2#

试试这个:

hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), key, data)
qc6wkl3g

qc6wkl3g3#

def make_payment(user)
    @key= SecureRandom.hex(10)
    #puts @key
    @secret_key = @key
    puts " this is the  public key #{@secret_key}"
    @access_key= generate_key
    puts " this is the access key #{@access_key}"
    @name= @user.name
    puts "#{@name}"
    @time= Time.now.in_time_zone("Nairobi")
    puts "This is the time request sent #{@time}"
    @server_key = SecureRandom.base64
    puts "This is the server key #{@server_key}"
    @data = 'This request is being made from Learnida for users to make a payment'
    @digest = OpenSSL::Digest.new('sha256')
    uri = URI.parse("https://learnida.com")

    @hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @secret_key, @access_key)
     puts "This is the HMAC #{@hmac}"
    req = Net::HTTP::Get.new(uri)
    req['Authorization'] = "TM-HMAC-SHA256 key=#{@access_key} ts=#{@time} sign=#{@hmac}"
    res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
    @hmacdigest= OpenSSL::HMAC.digest(@digest, @server_key, @data)
    puts" This is the HMAC:SHA-256:   #{@hmacdigest}" 
    #puts res.body
    #=> "\xF7\xBC\x83\xF40S\x84$\xB12\x98\xE6\xAAo\xB1C\xEFMY\xA1IF\x17Y\x97G\x9D\xBC-\x1A<\xD8"
    @sslkey= OpenSSL::HMAC.hexdigest(@digest, @server_key, @data)
    puts @sslkey
lvmkulzt

lvmkulzt4#

在我的例子(Ticketmatic)中,我必须像上面那样创建HMAC,并向包含HMAC的请求添加Authorization头。

hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret_key, access_key + name + time)
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "TM-HMAC-SHA256 key=#{access_key} ts=#{time} sign=#{hmac}"
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }

你可以找到完整的要点here
还有一个解释更多here的博客

相关问题