HMAC Signature
HMAC (Hash-based Message Authentication Code) is a technique used to verify both the integrity (ensuring data isn’t altered) and authenticity (ensuring data comes from a trusted source) of messages.
In cryptography, a message authentication code (MAC), sometimes known as an authentication tag, is a short piece of information used for authenticating and integrity-checking a message. In other words, it is used to confirm that the message came from the stated sender (its authenticity) and has not been changed (its integrity). The MAC value allows verifiers (who also possess a secret key) to detect any changes to the message content.
Any cryptographic hash function may be used in the calculation of an HMAC. The resulting MAC algorithm is termed HMAC-x, where x is the hash function used (e.g. HMAC-SHA256 or HMAC-SHA3-512). The cryptographic strength of the HMAC depends upon the cryptographic strength of the underlying hash function, the size of its hash output, and the size and quality of the key.
Example
Image we have a service that handle real money transactions, transferring money from one account to another. We need to make sure that the request is comes from trusted source and not being tampered or modified. We can use HMAC to do it because it offer both authenticating and integrity checks.
Our service are accepting this structure of payload message in JSON format.
Generate a key for the encryption and store it safely. In real-world scenario it's recommended that we create different secret for each user to make sure the authenticity of the request.
Below if how you can create a HMAC signature with SHA-256 in Golang. Replace the key
with your generated key and message
with your JSON payload.
This signature usually placed in the request header. And to verify the HMAC signature is simple. We just need to generate the signature again with request payload that we got in the backend service and match it with signature that we got in the request header.
References
Last updated