python - Python : HMAC Library vs Hashlib Produces Different Results 中的 HMAC SHA256

标签 python cryptography sha256 hmac

所以我一直在查看维基百科的 HMAC 伪代码,它看起来相对简单;如果您的 key 大小已经是块大小,则伪代码可归结为 3 行:

    o_key_pad ← key xor [0x5c * blockSize]   // Outer padded key
    i_key_pad ← key xor [0x36 * blockSize]   // Inner padded key

    return hash(o_key_pad ∥ hash(i_key_pad ∥ message))
这很容易转化为 Python:
ik = bytes([0x36 ^ b for b in k])
ok = bytes([0x5c ^ b for b in k])

print(hashlib.sha256(ok + bytearray.fromhex(hashlib.sha256(ik+msg).hexdigest())).hexdigest())
但这不会产生与使用 Python 的 HMAC 库相同的结果:
p = bytes("password", encoding='utf8')
k = bytearray.fromhex("eae1f9b8c78d0e0dbaeb3bc49fea3f0be9e9dc580c0b0ba09bcf5104713fda80")

x = hmac.new(k, digestmod='sha256')
x.update(p)
print(x.hexdigest())

ik = bytes([0x36 ^ b for b in k])
ok = bytes([0x5c ^ b for b in k])
print(hashlib.sha256(ok + bytearray.fromhex(hashlib.sha256(ik+p).hexdigest())).hexdigest())
最终生产
1b96a6d3473698c3592a99d752934b875f82cdd623230abc534f92e7b70cc251
57dcbe4ada890bcc8d3cc2e6072874e0d1a0d6d3f73ceb1ced8dad4f07b56e33
为什么?

最佳答案

在自定义实现中,缺少块大小键的填充,参见 here :

Keys shorter than blockSize are padded to blockSize by padding with zeros on the right


SHA256的块大小为64字节,见here .
以下 ptyhon 代码产生预期结果:
import hmac 
import hashlib

p = bytes("password", encoding='utf8')
k = bytearray.fromhex("eae1f9b8c78d0e0dbaeb3bc49fea3f0be9e9dc580c0b0ba09bcf5104713fda80")

x = hmac.new(k, digestmod='sha256')
x.update(p)
print(x.hexdigest())

k = bytearray.fromhex("eae1f9b8c78d0e0dbaeb3bc49fea3f0be9e9dc580c0b0ba09bcf5104713fda80".ljust(128,'0')) # pad with zeros
ik = bytes([0x36 ^ b for b in k])
ok = bytes([0x5c ^ b for b in k])
print(hashlib.sha256(ok + bytearray.fromhex(hashlib.sha256(ik+p).hexdigest())).hexdigest())
输出:
1b96a6d3473698c3592a99d752934b875f82cdd623230abc534f92e7b70cc251
1b96a6d3473698c3592a99d752934b875f82cdd623230abc534f92e7b70cc251
也可以验证here .

关于python - Python : HMAC Library vs Hashlib Produces Different Results 中的 HMAC SHA256,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64073659/

相关文章:

python命令行参数

java - Bouncy CastLe 的 ECDHE 安全性

java - 发送带有密文的 IV

python - 使用 Python 解密时,ROT2 密码会产生与预期不同的字符

c++ - 在 C++ 中使用 key 生成 HMAC SHA256 哈希

c - 实现 Lua SHA256 RFC-2104 兼容 HMAC 签名的最快路径?

python - 多线程和 ZMQ DEALER/REP hello world 不起作用

python - 将文件从文件夹复制到Python文件夹

python - 从文本文件读取时无法正确编码字符串(编码为 sha256...)

使用 disutils 的 setup.py 在 Linux 上进行 Python 打包并进行许多导入