2009-08-20 187 views
36

Amazon Product API現在需要對每個要嘗試生成使用Python的請求進行簽名。使用python中的字符串+密鑰計算SHA哈希值

的一步,我先掛了上是這個:1234567890欲瞭解更多信息:

假的‘祕密訪問鍵「使用上面我們的字符串計算符合RFC 2104-HMAC與SHA256散列算法’關於這一步,請參閱您的編程語言的文檔和代碼示例。「

給定一個字符串和一個密鑰(本例中爲1234567890)如何使用Python計算這個哈希值?

----------- ------------- UPDATE

使用HMAC.new第一個解決方案看起來是正確的但是我得到不同的結果比他們多。

http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?rest-signature.html

據亞馬遜的例子,當你哈希密鑰1234567890和下面的字符串

GET 
webservices.amazon.com 
/onca/xml 
AWSAccessKeyId=00000000000000000000&ItemId=0679722769&Operation=I 
temLookup&ResponseGroup=ItemAttributes%2COffers%2CImages%2CReview 
s&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z& 
Version=2009-01-06 

你應該得到以下特徵:'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='

我得到這個:'411a59403c9f58b4a434c9c6a14ef6e363acc1d1bb2c6faf9adc30e20898c83b'

+0

你可以找到這個有用的。 向亞馬遜簽名REST請求的算法在[http://stackoverflow.com/questions/1088715/how-to-sign-amazon-web-service-requests-from-the-python-app-engine/ 1343917#1343917](http://stackoverflow.com/questions/1088715/how-to-sign-amazon-web-service-requests-from-the-python-app-engine/1343917#1343917) – alsan 2009-08-28 14:53:02

回答

77
import hmac 
import hashlib 
import base64 
dig = hmac.new(b'1234567890', msg=your_bytes_string, digestmod=hashlib.sha256).digest() 
base64.b64encode(dig).decode()  # py3k-mode 
'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg=' 
+0

謝謝。這看起來是正確的,但我沒有像亞馬遜那樣得到同樣的結果。看到上面的更新。 – mymmaster 2009-08-20 15:38:19

+0

他們的哈希看起來像是base64編碼。 – Eli 2009-08-20 16:50:44

+0

就是這樣。需要在base64中進行編碼。謝謝。 – mymmaster 2009-08-20 17:07:02

2

http://docs.python.org/library/hashlib.html#module-hashlib(修改了一下):

import hashlib 
secretKey = "1234567890" 
m = hashlib.sha256() 

# Get string and put into givenString. 

m.update(givenString + secretKey) 
m.digest() 
+0

啊!我太遲了8秒! ;) – 2009-08-20 14:28:18

+1

你可能需要安裝py25-hashlib。我試圖在Python 2.5.4(2009年3月5日)上測試這段代碼,但得到了'ImportError:No module named _md5'。 – 2009-08-20 14:31:26

10
>>> import hmac 
>>> import hashlib 
>>> import base64 
>>> s = """GET 
... webservices.amazon.com 
... /onca/xml 
... AWSAccessKeyId=00000000000000000000&ItemId=0679722769&Operation=ItemLookup&ResponseGroup=ItemAttributes%2COffers%2CImages%2CReviews&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z&Version=2009-01-06""" 
>>> base64.b64encode(hmac.new("1234567890", msg=s, digestmod=hashlib.sha256).digest()) 
'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg=' 
+0

真正的解決方案大師... – 2015-03-11 03:07:45

6
import hmac 
import hashlib 
import base64 

digest = hmac.new(secret, msg=thing_to_hash, digestmod=hashlib.sha256).digest() 
signature = base64.b64encode(digest).decode() 

我知道這聽起來很愚蠢,但要確保你沒有意外對你的祕密尾隨空間。