In Go, you can use the crypto/hmac
package to implement HMAC for data integrity. Here's a step-by-step guide on how to use HMAC in Go:
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
)
var hmacKey = []byte("mySecretKey")
func calculateHMAC(data []byte) string {
h := hmac.New(sha256.New, hmacKey)
h.Write(data)
hmacValue := h.Sum(nil)
return hex.EncodeToString(hmacValue)
}
In this example, SHA-256 is used as the underlying hash function.
data := []byte("Hello, world!")
hmac := calculateHMAC(data)
Send the data and the computed HMAC to the receiver, along with any other required information.
On the receiver's side, verify the integrity of the data by recalculating the HMAC and comparing it with the received value:
receivedData := []byte("Hello, world!")
receivedHMAC := "..." // received HMAC value
calculatedHMAC := calculateHMAC(receivedData)
if calculatedHMAC == receivedHMAC {
// Data integrity validated
} else {
// Data has been tampered with
}
By comparing the calculated HMAC with the received HMAC value, you can ensure the integrity of the data. If the two values match, the data has not been tampered with. Otherwise, it means the data has been modified in transit.