Skip to main content

Insufficient HMAC Key Size

PY034
insufficient_key_size
CWE-326
⚠️ Warning

This rule identifies instances where the key provided to hmac.digest() or hmac.new() is considered too small relative to the digest algorithm's digest size. Using keys that are too short can compromise the integrity and security of the HMAC (Hash-based Message Authentication Code), making it less resistant to brute-force attacks.

HMAC is a mechanism for message authentication using cryptographic hash functions. The security of an HMAC depends significantly on the secret key's strength. A key that is shorter than the hash function's output size (digest size) can reduce the HMAC's effectiveness, making it more vulnerable to attacks. It is essential to use keys of adequate length to maintain the expected level of security, especially against brute-force attacks.

Ensure that the key length used with hmac.digest() or hmac.new() is at least equal to the digest size of the hash function being used. This compliance requirement helps maintain the cryptographic strength of the HMAC and protects the integrity of the message authentication process.

Example


warning
import hashlib
import hmac
import secrets


key = secrets.token_bytes(nbytes=32)
message = b"Hello, world!"
hmac.new(key, msg=message, digestmod=hashlib.sha3_384)

Remediation


Fix Iconfix

Adjust the key size to be at least the size of the digest.

import hashlib
import hmac
import secrets


key = secrets.token_bytes(nbytes=48)
message = b"Hello, world!"
hmac.new(key, msg=message, digestmod=hashlib.sha3_384)

False Positives


In the case of a false positive the rule can be suppressed. Simply add a trailing or preceding comment line with either the rule ID (PY034) or rule category name (insufficient_key_size).

Fix Iconfix
import hashlib
import hmac
import secrets


key = secrets.token_bytes(nbytes=32)
message = b"Hello, world!"
# suppress: PY034
hmac.new(key, msg=message, digestmod=hashlib.sha3_384)

See also