Insufficient hmac Key Size
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
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
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)
See also
- hmac — Keyed-Hashing for Message Authentication
- secrets — Generate secure random numbers for managing secrets
- CWE-326: Inadequate Encryption Strength
New in version 0.4.3