我正在尝试通过REST Web API连接到DynamoDB,它要求我使用HMAC-SHA256生成签名。我已经使SHA-256工作正常,但是我似乎无法使HMAC工作,以下是C++代码(使用OpenSSL):
string hmac(string key, string msg)
{
unsigned char hash[32];
HMAC_CTX hmac;
HMAC_CTX_init(&hmac);
HMAC_Init_ex(&hmac, &key[0], key.length(), EVP_sha256(), NULL);
HMAC_Update(&hmac, (unsigned char*) &msg[0], msg.length());
unsigned int len = 32;
HMAC_Final(&hmac, hash, &len);
HMAC_CTX_cleanup(&hmac);
stringstream ss;
for (int i = 0; i < len; i++)
{
ss << hex << ( unsigned int )hash[i];
}
return ss.str();
}
这里是调用hmac的代码
/*********************************************CALCULATE SIGNATURE****************************************************************/
string AWS4 = "AWS4" + secretKey;
string Kdate = hmac(AWS4.data(), dateStamp);
string Kregion = hmac(Kdate.data(), region);
string Kservice = hmac(Kregion.data(), service);
string signingkey = hmac(Kservice.data(), "aws4_request");
string signature = hmac(signingkey.data(), stringToSign);
string authoritzationHeader = algorithm + " Credential=" + accessKey + "/" + credential_scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature;
这是我参考的Python代码:
def sign(key, msg):
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
def getSignatureKey(key, date_stamp, regionName, serviceName):
kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp)
kRegion = sign(kDate, regionName)
kService = sign(kRegion, serviceName)
kSigning = sign(kService, 'aws4_request')
print 'Kdate: ' + kDate
print 'Kregion: ' + kRegion
print 'Kservice: ' + kService
return kSigning
相同的值产生不同的结果。有人能帮我解释一下这是为什么吗?谢谢。
hmac()
吗?Python代码似乎在密钥字符串前面添加了“AWS4”。这对于它所做的事情似乎非常重要。 - WhozCraig