在Python编程范围内,我尝试用Python编写hmac-sha1函数。代码如下所示。但返回的值似乎不是正确的值。
计算的 HMAC:cb1e45d7fb852695e63731edb4f58547f9249ad9
值必须是:de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
我的代码中是否有任何错误以及如何修复它以获得预期值。
谢谢
#HMAC
import hashlib
toHex = lambda x:"".join([hex(ord(c))[2:].zfill(2) for c in x]) #return string
# initiate i_pad and o_pad
i_pad = int('36'*64,16)
o_pad = int('5C'*64,16)
def hmac(key,msg):
print('key=',key,'msg=',msg)
h_key = toHex(key)
h_msg = int(toHex(msg),16)
if len(h_key)>128:
#hash key if len(key) > 64 bytes
h_key = hashlib.sha1(h_key.encode('ascii'))
while len(h_key)<128:
# padding key to 64 bytes
h_key+='00'
h_key = (int(h_key,16))
i_key_pad = h_key ^ i_pad
o_key_pad = h_key ^ o_pad
#first pass
first_msg=hex(i_key_pad)[2:] + hex(h_msg)[2:]
hash1 = hashlib.sha1(first_msg.encode('ascii'))
#second pass
second_msg = hex(o_key_pad)[2:] + hash1.hexdigest()
hash2 = hashlib.sha1(second_msg.encode('ascii'))
return hash2.hexdigest()
def test():
hash = hmac("key", "The quick brown fox jumps over the lazy dog")
print('computed hmac',hash)
print('value must be de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9')
test1()
我已经重写了字节代码,但结果仍然不正确!
from hashlib import sha1
import sys
def encrypt1(var, key):
return bytes(a ^ b for a, b in zip(var, key))
#The second one uses int.from_bytes and int.to_bytes: 20 x faster
def encrypt2(var, key):
key = key[:len(var)]
int_var = int.from_bytes(var, sys.byteorder)
int_key = int.from_bytes(key, sys.byteorder)
int_enc = int_var ^ int_key
return int_enc.to_bytes(len(var), sys.byteorder)
key, msg = b'key', b'The quick brown fox jumps over the lazy dog'
# initiate i_pad and o_pad
i_pad = b'6'*64 # chr(0x36)='6'
o_pad = b'\\'*64 # chr(0x5C)='\\'
print(i_pad)
print(o_pad)
key = key+b'0'*(64-len(key))
print(key,len(key))
i_key_pad = encrypt2(i_pad, key)
print(i_key_pad)
o_key_pad = encrypt2(o_pad, key)
print(o_key_pad)
#first pass
first_msg = i_key_pad + msg
print(first_msg, len(first_msg))
hash1 = sha1(first_msg)
#print(hash1.hexdigest())
print(hash1.digest())
#second pass
second_msg = o_key_pad + hash1.digest()
print(second_msg, len(second_msg))
hash2 = sha1(second_msg)
print(hash2.hexdigest())
print('de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9 expected')`
我是一名优秀的程序员,十分优秀!