在python中使用字符串+密钥计算SHA哈希

时间:2009-08-20 14:23:36

标签: python hash sha256

亚马逊产品API现在需要一个签名,其中包含我正在尝试生成Python的所有请求。

我接下来的步骤就是这个:

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

给定字符串和密钥(在本例中为1234567890),如何使用Python计算此哈希值?

-----------更新-------------

使用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'

6 个答案:

答案 0 :(得分:93)

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

答案 1 :(得分:11)

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

答案 2 :(得分:11)

import hmac
import hashlib
import base64

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

我知道这听起来很愚蠢,但要确保你的秘密没有意外的空间。

答案 3 :(得分:3)

来自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()

答案 4 :(得分:1)

如果您有字符串秘密和字符串令牌,它可能会有所帮助(我知道可能为时已晚,但以防万一它对某人有用)。所有三个选项在 python 3 中都对我有用 -

import hmac
import hashlib
import base64

access_token = 'a'
app_secret = 'b'

access_token = <your token in string format>
app_secret = <your secret access key in string format>

# use any one, all three options work.
# OPTION 1 (it works)
# digest = hmac.new(app_secret.encode('UTF-8'),
#                   access_token.encode('UTF-8'), hashlib.sha256)
# OPTION 2 (it works)
# digest = hmac.new(str.encode(app_secret),
#                   str.encode(access_token), hashlib.sha256)
# OPTION 3 (it works)
digest = hmac.new(bytes(app_secret, 'UTF-8'),
                bytes(access_token, 'UTF-8'), hashlib.sha256)
signature = digest.hexdigest()
print(signature)

答案 5 :(得分:0)

如果您尝试使用Python3将用户注册到AWS Cognito,则可以使用以下代码。

#For the SecretHash 
import hmac
import hashlib
import base64   

//Please note that the b in the secretKey and encode('utf-8') are really really important. 
secretKey = b"secret key that you get from Coginito -> User Pool -> General Settings -> App Clients-->Click on Show more details -> App client secret  "
 clientId = "Coginito -> User Pool -> General Settings -> App Clients-->App client id"
 digest = hmac.new(secretKey,
              msg=(user_name + clientId).encode('utf-8'),
              digestmod=hashlib.sha256
             ).digest()
 secrethash = base64.b64encode(digest).decode()

上面的用户名user_name与您要在认知模式中注册的用户相同

client = boto3.client('cognito-idp', region_name='eu-west-1' )

response = client.sign_up(
                    ClientId='Coginito -> User Pool -> General Settings -> App Clients-->App client id',
                    Username='Username of the person you are planning to register',
                    Password='Password of the person you are planning to register',
                    SecretHash=secrethash,
                    UserAttributes=[
                        {
                            'Name': 'given_name',
                            'Value': given_name
                        },
                        {
                            'Name': 'family_name',
                            'Value': family_name
                        },
                        {
                            'Name': 'email',
                            'Value': user_email
                        }
                    ],
                    ValidationData=[
                        {
                            'Name': 'email',
                            'Value': user_email
                        },
                    ]
相关问题