【发布时间】:2018-01-24 19:28:10
【问题描述】:
我的问题与Translation from Python to JavaScript: HMAC-SHA256 非常相似,但该问题从未得到解答。
以下 Python 代码生成正确的哈希:
def sign_api_request(api_secret, api_key, method, url):
encoded_url = urllib.parse.quote(url.lower(), '').lower()
timestamp = int(time.time())print("timestamp: " + str(timestamp))
nonce = str(uuid.uuid4())
signature = api_key + method + encoded_url + str(timestamp) + nonce
secret_bytes = base64.b64decode(api_secret)
signature_bytes = signature.encode('UTF8')
signature_hash = hmac.new(secret_bytes, signature_bytes, hashlib.sha256).digest()
base64_signature_hash = base64.b64encode(signature_hash).decode()
print(base64_signature_hash)
我正在尝试使用 Javascript(作为 Postman 预请求脚本)生成相同的哈希字符串。这是我得到的:
function epochTime() {
var d = new Date();
var t = d.getTime();
var o = t + "";
return o.substring(0, 10);
}
function newGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : r & 0x3 | 0x8; return v.toString(16); });
}
var uri_path = encodeURIComponent(request.url.toLowerCase()).toLowerCase();
var payload = uri_path; //.toLowerCase();
timestamp = epochTime();
nonce = newGuid();
signature = environment.api_key + "GET" + payload + timestamp + nonce;
secret_bytes = atob(environment.api_secret);
var hash = CryptoJS.HmacSHA256(signature, secret_bytes);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
var sig = "amx " + environment.api_key + ":" + hashInBase64 + ":" + nonce + ":" + timestamp;
postman.setGlobalVariable("signature", sig);
如果我使用相同的 timestamp 和 nonce(通过显式设置而不是在运行时生成它们)和相同的 api_key 和 api_secret(在调用中保持不变),我希望得到相同的结果sig (Javascript) 中的值,就像我在 base64_signature_hash (Python) 中所做的一样,但事实并非如此。
我知道这可能是编码问题,但我的 js-fu 很弱。有什么想法吗?
编辑添加:每个使用的method 和url 也是相同的。
【问题讨论】:
标签: javascript python hmac cryptojs