Skip to content

hmac — weak key

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

hmac_new_weak_key_hashlib_sha3_384.py
1
2
3
4
5
6
7
8
import hashlib
import hmac
import secrets


key = secrets.token_bytes(None)
message = b"Hello, world!"
hmac.new(key, msg=message, digestmod=hashlib.sha3_384)
Example Output
> precli tests/unit/rules/python/stdlib/hmac/examples/hmac_new_weak_key_hashlib_sha3_384.py
⚠️  Warning on line 8 in tests/unit/rules/python/stdlib/hmac/examples/hmac_new_weak_key_hashlib_sha3_384.py
PY034: Inadequate Encryption Strength
The given key is only '32' bytes which is insufficient for the 'hashlib.sha3_384' algorithm.

Remediation

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

hmac_new_weak_key_hashlib_sha3_384.py
1
2
3
4
5
6
7
8
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)

Default Configuration

enabled = true
level = "warning"

See also

New in version 0.4.3