如何在python代码中使用SHA256-HMAC?

2024-06-07 18:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

I am taking message and key from this URL

import hmac
import hashlib
import base64
my = "/api/embedded_dashboard?data=%7B%22dashboard%22%3A7863%2C%22embed%22%3A%22v2%22%2C%22filters%22%3A%5B%7B%22name%22%3A%22Filter1%22%2C%22value%22%3A%22value1%22%7D%2C%7B%22name%22%3A%22Filter2%22%2C%22value%22%3A%221234%22%7D%5D%7D"
key = "e179017a-62b0-4996-8a38-e91aa9f1"
print(hashlib.sha256(my + key).hexdigest())

我得到的结果是:

2df1d58a56198b2a9267a9955c31291cd454bdb3089a7c42f5d439bbacfb3b88

预期结果:

adcb671e8e24572464c31e8f9ffc5f638ab302a0b673f72554d3cff96a692740

Tags: andkeyfromimportapiurlmessagemy
2条回答

为您提供一些易于使用的代码:

import hmac
import hashlib
import binascii

def create_sha256_signature(key, message):
    byte_key = binascii.unhexlify(key)
    message = message.encode()
    return hmac.new(byte_key, message, hashlib.sha256).hexdigest().upper()

create_sha256_signature("E49756B4C8FAB4E48222A3E7F3B97CC3", "TEST STRING")

您根本没有在代码中使用hmac

使用hmac、从密钥、消息构造HMAC对象并通过传入其构造函数标识散列算法的典型方法:

h = hmac.new( key, my, hashlib.sha256 )
print( h.hexdigest() )

它应该输出

adcb671e8e24572464c31e8f9ffc5f638ab302a0b673f72554d3cff96a692740

你的示例数据。

相关问题 更多 >

    热门问题