在 python 中重新创建 node.js HMAC 时遇到问题
Having trouble recreating node.js HMAC in python
我正在尝试在 python 中重新创建此 node.js 脚本:
const { createHmac } = require('crypto');
const generateHMAC = (uuid2, uuid1, timestamp) => {
return createHmac('sha256', uuid2.substring(0, 10))
.update(uuid2 + uuid1 + timestamp)
.digest('hex');
}
const uuid1 = '00210078-008a-00b3-00fc-005e009b00a7'
const uuid2 = '00eb0079-0033-00a2-00ab-005c003900b5'
const timestamp = '1643438223104'
const hmac = generateHMAC(uuid2, uuid1, timestamp)
console.log(hmac)
我收到 'TypeError: Strings must be encoded before hashing' 错误。但是我不太确定我是否走在正确的轨道上。我当前的 python 脚本:
import random, os, gmpy2, hmac, time, hashlib, base64
def generate_hmac(uuid2, uuid1, timestamp):
message = uuid2 + uuid1 + timestamp
key = uuid2[0:10]
hmac_result = hmac.new(bytes(key, encoding='utf-8'), message, hashlib.sha256).hexdigest()
print(hmac_result)
if __name__ == '__main__':
uuid1 = '00210078-008a-00b3-00fc-005e009b00a7'
uuid2 = '00eb0079-0033-00a2-00ab-005c003900b5'
timestamp = '1643438223104'
generate_hmac(uuid2=uuid2, uuid1=uuid1, timestamp=timestamp)
- 请原谅乱七八糟的导入,这只是脚本的一部分。
非常感谢任何帮助!
我设法解决了这个问题,这是我的结果:
def generate_hmac(uuid2, uuid1, timestamp):
message = uuid2 + uuid1 + timestamp
messageBytes = bytes(message.encode('utf-8'))
key = uuid2[0:10]
keyBytes = bytes(key.encode('utf-8'))
hmac_result = hmac.new(keyBytes, messageBytes, hashlib.sha256).hexdigest()
在 hmac.new() 函数中使用之前,我没有对我的消息和密钥进行编码。
我正在尝试在 python 中重新创建此 node.js 脚本:
const { createHmac } = require('crypto');
const generateHMAC = (uuid2, uuid1, timestamp) => {
return createHmac('sha256', uuid2.substring(0, 10))
.update(uuid2 + uuid1 + timestamp)
.digest('hex');
}
const uuid1 = '00210078-008a-00b3-00fc-005e009b00a7'
const uuid2 = '00eb0079-0033-00a2-00ab-005c003900b5'
const timestamp = '1643438223104'
const hmac = generateHMAC(uuid2, uuid1, timestamp)
console.log(hmac)
我收到 'TypeError: Strings must be encoded before hashing' 错误。但是我不太确定我是否走在正确的轨道上。我当前的 python 脚本:
import random, os, gmpy2, hmac, time, hashlib, base64
def generate_hmac(uuid2, uuid1, timestamp):
message = uuid2 + uuid1 + timestamp
key = uuid2[0:10]
hmac_result = hmac.new(bytes(key, encoding='utf-8'), message, hashlib.sha256).hexdigest()
print(hmac_result)
if __name__ == '__main__':
uuid1 = '00210078-008a-00b3-00fc-005e009b00a7'
uuid2 = '00eb0079-0033-00a2-00ab-005c003900b5'
timestamp = '1643438223104'
generate_hmac(uuid2=uuid2, uuid1=uuid1, timestamp=timestamp)
- 请原谅乱七八糟的导入,这只是脚本的一部分。
非常感谢任何帮助!
我设法解决了这个问题,这是我的结果:
def generate_hmac(uuid2, uuid1, timestamp):
message = uuid2 + uuid1 + timestamp
messageBytes = bytes(message.encode('utf-8'))
key = uuid2[0:10]
keyBytes = bytes(key.encode('utf-8'))
hmac_result = hmac.new(keyBytes, messageBytes, hashlib.sha256).hexdigest()
在 hmac.new() 函数中使用之前,我没有对我的消息和密钥进行编码。