API Reference › Crypto › Crypto.verify_hmac
method

Crypto.verify_hmac

Crypto.verify_hmac(key, msg, mac) -> bool

Recomputes HMAC-SHA256(key, msg) and compares it to the supplied mac hex string, returning true only if they match. The comparison is constant-time: it never stops early on the first differing character, so it does not leak — through how long the check took — how many leading bytes of a forged tag happened to be right. That leak is exactly what lets an attacker guess a MAC one byte at a time, which is why you should always verify with this and never with ==. A mismatched length returns false immediately (the length of a MAC is not a secret).

Parameters

keythe shared secret used to sign
msgthe payload as received
macthe hex tag to check, e.g. from Crypto.hmac_sha256

Example

program CheckSave {
  entry {
    let key = "s3cret"
    let payload = "score=9001;level=12"
    let mac = Crypto.hmac_sha256(key, payload)
    if Crypto.verify_hmac(key, payload, mac) {
      print(1)   # untampered
    } else {
      print(0)   # altered or forged
    }
  }
}
← All symbols