簡體   English   中英

Ruby HMAC-SHA與Python不同

[英]Ruby HMAC-SHA Differs from Python

我正在將一些現有代碼從Python重寫為Ruby,而且我遇到了一個我似乎無法弄清楚的奇怪錯誤。 這里我們有Python代碼(可以工作):

import sha, hmac
data = 'sampledata'
data = data.encode('ascii')
des_key = hmac.new(data + "\0", "SUPERSECRET", sha).digest()[0:8]

輸出:0x64F461D377D9930C

而Ruby(我是新手)的代碼:

require 'openssl'
digest  = OpenSSL::Digest::SHA.new
data = 'sampledata'
data.encode!('ascii')
puts OpenSSL::HMAC.hexdigest(digest, "SUPERSECRET", data + "\0")[0, 16]

輸出:0x563FDAF11E63277C

什么可能導致這種差異?

你犯了兩個錯誤:

  1. Python的hmac.new采用密鑰,方法,摘要 - 所以你應該寫

    hmac.new(“SUPERSECRET”,數據+“\\ 0”,sha)

  2. Ruby中OpenSSL :: Digest的默認摘要方法不是SHA1(我不確定它是什么)。 你應該使用:

    OpenSSL的:: HMAC.hexdigest( 'SHA1', “絕密”,數據+ “\\ 0”)[0,16]

兩種方法(首先在Python中,第二在Ruby中)返回相同的輸出。

除了Guy Adini的回答 - 在Ruby SHA中不同於python shasha1 (在sha.pyfrom hashlib import sha1 as sha ):

from hashlib import *
import hmac
data = 'sampledata'
data = data.encode('ascii')

algo = [sha1, sha224, sha256, sha512]
for al in algo:
    print al().name, hmac.new("SUPERSECRET", data + "\0", al).hexdigest()[0:16]

生產:

sha1 50c61ea49195f03c
sha224 fd6a418ee0ae21c8
sha256 79deab13bd7b041a
sha512 31561f9c9df69ab2

在Ruby中:

require 'openssl'
data = 'sampledata'
data.encode!('ascii')
%w(sha sha1 sha224 sha256 sha512).each do |al|
  puts "#{al}: #{OpenSSL::HMAC::hexdigest(al, "SUPERSECRET", "#{data}\0")[0,16]}"
end

生產:

sha: 563fdaf11e63277c
sha1: 50c61ea49195f03c
sha224: fd6a418ee0ae21c8
sha256: 79deab13bd7b041a
sha512: 31561f9c9df69ab2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM