HMAC原理

根据HMAC算法描述实现

def hashed_mac(key, data, hash_func):
    if not isinstance(key, bytes):
        raise TypeError('key must be bytes')
    if not isinstance(data, bytes):
        raise TypeError('data must be bytes')

    if len(key) > 64:
        key = hash_func(key).digest()

    key += b'\x00' * (64 - len(key))

    v = bytearray(64)
    array_key = bytearray(key)

    for idx, i in enumerate(array_key):
        v[idx] = i ^ 0x36
    ipad = bytes(v)

    for idx, i in enumerate(array_key):
        v[idx] = i ^ 0x5c
    opad = bytes(v)

    return hash_func(opad + hash_func(ipad + data).digest())

import hashlib
import hmac

# 0e2564b7e100f034341ea477c23f283b
print(hashed_mac(b'hello', b'world', hashlib.md5).hexdigest())
print(hmac.new(b'hello', b'world', hashlib.md5).hexdigest())

# 8a3a84bcd0d0065e97f175d370447c7d02e00973
print(hashed_mac(b'hello', b'world', hashlib.sha1).hexdigest())
print(hmac.new(b'hello', b'world', hashlib.sha1).hexdigest())

# 7c3588779a5defb5f93cfb5e60975e82
print(hashed_mac(b'hello' * 20, b'world' * 5, hashlib.md5).hexdigest())
print(hmac.new(b'hello' * 20, b'world' * 5, hashlib.md5).hexdigest())

# d283c302f555721058733ddba7b967a7d09732cc
print(hashed_mac(b'hello' * 30, b'world' * 100, hashlib.sha1).hexdigest())
print(hmac.new(b'hello' * 30, b'world' * 100, hashlib.sha1).hexdigest())

版权声明:本文为J_z10原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。