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())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值