如何在python中计算AWS API签名(v4)?

时间:2012-10-22 20:21:04

标签: python amazon-web-services hmac amazon-glacier

我正在尝试使用AWS文档提供的example requestsexample functions为Amazon Glacier上传请求生成签名,但我无法使其正常运行。在这一点上,我确信我错过了一些非常明显的东西:

#!/bin/env python

import hmac
import hashlib

# This string to sign taken from: http://docs.amazonwebservices.com/amazonglacier/latest/dev/amazon-glacier-signing-requests.html#example-signature-calculation
sts = """AWS4-HMAC-SHA256
20120525T002453Z
20120525/us-east-1/glacier/aws4_request
5f1da1a2d0feb614dd03d71e87928b8e449ac87614479332aced3a701f916743"""

# These two functions taken from: http://docs.amazonwebservices.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).hexdigest()

# The fake secret key is provided by the referenced docs
def getSignatureKey():
    kDate = sign(("AWS4" + "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY").encode('utf-8'), "20120525")
    kRegion = sign(kDate, "us-east-1")
    kService = sign(kRegion, "glacier")
    kSigning = sign(kService, "aws4_request")
    return kSigning

signature = sign(getSignatureKey(), sts)
print signature

如果我运行我的程序,我会得到以下哈希:

$ python test.py
3431315da57da4df28f92895c75364d94b36c745896ad3e580c0a6ae403b1e05

然而,文档明确指出:

  

如果使用了秘密访问密钥wJalrXUtnFEMI / K7MDENG / bPxRfiCYEXAMPLEKEY,则计算出的签名为:

     

3ce5b2f2fffac9262b4da9256f8d086b4aaf42eba5f111c21681a65a127b7c2a

我错过了什么?

1 个答案:

答案 0 :(得分:6)

您的功能在某方面与他们的功能不同。你在做什么

def sign(key, msg):
  return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).hexdigest()

但他们正在做

def sign(key, msg):
  return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

所以你的派生密钥错了。您只希望在流程的最后一步使用hexdigest,而不是在计算签名密钥时使用。