# Crypto : HMAC
*HMAC -> Hashed Message Authentication Code*
- https://datatracker.ietf.org/doc/html/rfc2104.html
- https://en.wikipedia.org/wiki/HMAC
Uses a cryptographic hash function combined with a shared secret to perform authentication.
When HMAC is used with SHA-1, it's called HMAC-SHA1. When used with SHA-256, it's HMAC-SHA256, etc.
**Components**
- H -> hash function
- B -> block length of hash function (usually 64)
- L -> byte-length of hash outputs (20 for SHA-1, 32 for SHA-256, etc.)
- K -> key of any length; if larger than B, will be hashed to make smaller; recommended length is L (less is weak and more is worthless)
- ipad -> the byte 0x36 repeated B times
- opad -> the byte 0x5C repeated B times
**Algorithm**
To compute HMAC over the data `"text"`, we perform:
```
H( K XOR opad, H( K XOR ipad, text ) )
```
## Python
```python
import hmac
h = hmac.new( key: bytes, msg: bytes = None, digestmod ) -> hmac.HMAC
# digestmod = string or function of hashlib algorithm
h.name -> str # ex: "hmac-sha1"
h.update( msg: bytes ) # append more data
h.digest_size -> int # ex: 20
h.digest() -> bytes # b"F\xb4\xecXa\x17\x15M\xac\xd4\x9dfN]c\xfd\xc8\x8e\xfbQ"
h.hexdigest() -> str # "46b4ec586117154dacd49d664e5d63fdc88efb51"
# like hmac.new( ... ).digest() but faster — if msg fits in memory
hmac.digest( key: bytes, msg: bytes, digest ) # digest = string of hashlib algorithm
```