簡體   English   中英

從 Python 到 Javascript 的加密 hmac 轉換

[英]Crypto hmac conversion from Python to Javascript

我正在嘗試將以下 function 從 Python 轉換為 Javascript。目前專注於簽名的生成。

def prepare_url(self, segments, params={}):
        if self.token is not None:
            sig = hmac.new(self.token.key.encode(), digestmod=hashlib.sha1)
            sig.update(self.method.lower().encode())
            sig.update(self.service.lower().encode())
            

            ts = self.get_timestamp(self.token.server_offset)
            sig.update(ts.encode())
            params["timestamp"] = ts

            sig.update(self.token.identifier.lower().encode())
 
            params["signature-method"] = "auth"
            params["signature-version"] = self.version
            params["signature"] = base64.standard_b64encode(sig.digest())
 
        self.url = "%s/%s/%d/" % (self.base_path, self.service, self.version)
        self.url += "/".join([urllib.parse.quote(s) for s in segments])
        if params:
            self.url += "?%s" % urllib.parse.urlencode(params)

在 Javascript 中,我正在使用加密庫並具有以下代碼:

import crypto from 'crypto';

const KEY = '5d016f32-452f-4b9b-8e81-641e14d4d98c';
const METHOD = 'get';
const SERVICE = 'data';
const date = (new Date()).toISOString().slice(0, 19);

const encoded = crypto.createHash('sha1')
    .update(KEY)
    .update(METHOD.toLowerCase())
    .update(SERVICE.toLowerCase())
    .update(date)
    .digest('hex');
console.log(encoded);

const baseEncoded = btoa(encoded);
console.log(baseEncoded);

但是,結束代碼不可比較。

Python 使用給定輸入生成: b'oV4RJ6pAz+hxZsxeQthx8gZrhAY='

Javascript 生成: YTZjMmIyYjQzOGEwZGUxZTU1YTNjMWVlYjA3MTA3NTFmODc0MDM3ZQ==

我四處搜索,但找不到要更改的內容才能使這項工作正常進行。 在 python 中,摘要是 hashlib.sha1,這在加密中不可用。

任何指針?

以下是 Python 在每個更新步驟中生成的代碼。

-----> key: b'bnAcIlriz+t4hTQLBrnjI1aeXBI='
-----> method: b'rc1Y6wKZo8pDKHmhjVNDkhcVNKM='
-----> Service: b'/urBh6Yqk6QI39JhYtSMI9P9QS8='
-----> Time: 5d016f32-452f-4b9b-8e81-641e14d4d98c
-----> Identifier: b'oV4RJ6pAz+hxZsxeQthx8gZrhAY='
-----> FINAL: b'oV4RJ6pAz+hxZsxeQthx8gZrhAY='

解決方案:

const encoded = crypto.createHmac('sha1', key)
    .update(METHOD.toLowerCase())
    .update(SERVICE.toLowerCase())
    .update(date)
    .update(identify)
    .digest('base64');

根據@PresidentJamesK.Polk 的反饋,我能夠弄清楚這一點。

const encoded = crypto.createHmac('sha1', key)
    .update(METHOD.toLowerCase())
    .update(SERVICE.toLowerCase())
    .update(date)
    .update(identify)
    .digest('base64');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM