Ruby hmac sha256哈希值因变量与文字而异

时间:2016-04-18 16:19:44

标签: ruby hash string-concatenation sha256 hmac

在散列函数中使用变量时生成的HMAC SHA256散列更改比使用文字更改。

我必须连接4个参数以生成使用密钥进行哈希处理的消息字符串。连接的消息字符串生成不同的散列,而不是使用message的值作为文字。

require 'base64'
require 'openssl'

securityKey = 'A93reRTUJHsCuQSHR+L3GxqOJyDmQpCgps102ciuabc='
content = 'hello'
id = '1000000855'
tsp = '1460852115'
guid = '75c6016eaa1e43b4807ba25232797714'

contentmd5 = Base64.encode64(OpenSSL::Digest::MD5.digest(content))
inputString = id + tsp + guid + contentmd5
puts inputString
#Input String is 
#'1000000855146085211575c6016eaa1e43b4807ba25232797714XUFAKrxLKna5cZ2REBfFkg=='

digest = OpenSSL::Digest.new('sha256')
hmac = OpenSSL::HMAC.digest(digest, securityKey, inputString)
securityToken = Base64.encode64(hmac)
puts securityToken
#Hash generated is 7ihOEZNeoJMwjLt84I8WfN5b0VwgYNOg8abPA3nZ0SM=

digest = OpenSSL::Digest.new('sha256')
hmac = OpenSSL::HMAC.digest(digest, securityKey, '1000000855146085211575c6016eaa1e43b4807ba25232797714XUFAKrxLKna5cZ2REBfFkg==')
securityToken = Base64.encode64(hmac)
puts securityToken
#Hash generated is gPNytNGMbhg8b27rklqmEK/9xjNAcOq+7nldzyDL4g0=

1 个答案:

答案 0 :(得分:2)

看起来像Base64.encode64附加一个" \ n"到它的输出结束所以

来自docs

  

encode64(bin)返回Base64编码的   bin的版本。此方法符合RFC 2045.换行符   添加到每60个编码字符。

contentmd5 = Base64.encode64(OpenSSL::Digest::MD5.digest(content))

返回

"XUFAKrxLKna5cZ2REBfFkg==\n"

 "XUFAKrxLKna5cZ2REBfFkg=="

-

您可以使用 strict_encode64 来不包含换行符,所以:

contentmd5 = Base64.strict_encode64(OpenSSL::Digest::MD5.digest(content))

返回

 => "XUFAKrxLKna5cZ2REBfFkg=="