# Python Hmac Module

The `hmac` module implements the HMAC algorithm as described by RFC 2104. HMAC stands for Keyed-Hashing for Message Authentication.

## Importing the Module

```python
import hmac
```

## Creating an HMAC Object

To create an HMAC object, you use the `hmac.new()` function. It requires a key and a message (optional at creation), and a digest module (default is usually MD5 in older versions, but it's best to specify, e.g., `hashlib.sha256`).

```python
import hmac
import hashlib

key = b'secret-key'
msg = b'message-to-authenticate'

h = hmac.new(key, msg, hashlib.sha256)
```

## Getting the Digest

### `digest()`

Returns the digest of the bytes passed to the `update()` method so far.

```python
print(h.digest())
```

### `hexdigest()`

Returns the digest as a string of hexadecimal digits.

```python
print(h.hexdigest())
```

## Verifying Signatures

To prevent timing attacks, you should use `hmac.compare_digest()` instead of the `==` operator when verifying signatures.

```python
import hmac

received_digest = "..." # The digest you received
calculated_digest = h.hexdigest()

if hmac.compare_digest(received_digest, calculated_digest):
    print("Signature matches")
else:
    print("Signature does not match")
```

[[programming/python/python]]