HMAC (Hash-based Message Authentication Code) is a mechanism for message authentication using cryptographic hash functions. It combines a secret key with the message data and applies a hash function to produce a fixed-size authentication code. HMAC provides both data integrity and authenticity verification, ensuring that the message hasn't been tampered with and comes from someone who possesses the secret key.
The security of HMAC depends on both the underlying hash function and the secrecy of the key. HMAC-SHA256 is widely recommended for new applications, while HMAC-MD5 and HMAC-SHA1 are considered less secure but still used in legacy systems. The secret key should be randomly generated and kept confidential. A longer key (256 bits or more) provides better security against brute-force attacks.
HMAC is commonly used in API authentication, digital signatures, and secure communications. Unlike simple hashing, HMAC requires knowledge of the secret key to generate or verify the authentication code. This makes it ideal for scenarios where you need to verify that data came from a trusted source and hasn't been modified during transmission.