使用python中的字符串+密钥计算SHA哈希 [英] Calculating a SHA hash with a string + secret key in python

查看:795
本文介绍了使用python中的字符串+密钥计算SHA哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亚马逊产品API现在需要每次请求的签名,我试图生成使用Python的Python。



我挂断的步骤是这样的:

/ p>

使用上面的字符串和我们的虚拟秘密访问密钥:1234567890,通过SHA256哈希算法计算符合RFC 2104的HMAC。有关此步骤的更多信息,请参阅为您的编程语言提供文档和代码示例。



给定一个字符串和一个密钥(本例中为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&安培;服务= AWSECommerceService&安培;时间戳= 2009-01-01T12%3A00%3A00Z&安培;
版本= 2009-01-06

您应该得到以下签名:'Nace + U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg ='



我得到这个:'411a59403c9f58b4a434c9c6a14ef6e363acc1d1bb2c6faf9adc30e20898c83b'

解决方案

  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 ='


Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.

The step I get hung up on is this one:

"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more information about this step, see documentation and code samples for your programming language."

Given a string and a secret key (in this case 1234567890) how do I calculate this hash using Python?

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

The first solution using HMAC.new looks correct however I'm getting a different result than they are.

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

According to Amazon's example when you hash the secret key 1234567890 and the following string

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

You should get the following signature: 'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='

I am getting this: '411a59403c9f58b4a434c9c6a14ef6e363acc1d1bb2c6faf9adc30e20898c83b'

解决方案

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='

这篇关于使用python中的字符串+密钥计算SHA哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆