Skip to main content

hmac function

Applies to: check marked yes Databricks SQL check marked yes Databricks Runtime 19 and above

Returns the keyed-hash message authentication code (HMAC) of message using key and a hash algorithm.

An HMAC verifies both the integrity and the authenticity of a message using a shared secret key: a recipient who holds the same key can recompute the code and confirm the message was not altered and came from a party that knows the key. Common uses include signing API requests, validating webhook payloads, and deriving signing keys by chaining HMAC calls (for example, AWS Signature Version 4).

Syntax​

hmac(key, message [, algorithm])

Arguments​

  • key: A BINARY expression. The secret key.
  • message: A BINARY expression. The message to authenticate.
  • algorithm: An optional STRING expression describing the hash algorithm. The default is SHA-256.

Returns​

A BINARY.

The result is the raw MAC bytes. To obtain a textual representation, wrap the result with hex function or base64 function. Because the result is BINARY, you can feed it back in as the key of another hmac call to chain key derivations.

algorithm must be one of the following (case-insensitive, with or without the hyphen, for example both SHA-256 and SHA256):

  • 'SHA-224'
  • 'SHA-256': This is the default.
  • 'SHA-384'
  • 'SHA-512'
  • 'SHA-1'
  • 'MD5'

If any argument is NULL, the result is NULL.

Common error conditions​

Examples​

SQL
> SELECT hex(hmac('key', 'message'));
6E9EF29B75FFFC5B7ABAE527D58FDADB2FE42E7219011976917343065F58ED4A

> SELECT hex(hmac('key', 'message', 'SHA-512'));
E477384D7CA229DD1426E64B63EBF2D36EBD6D7E669A6735424E72EA6C01D3F8B56EB39C36D8232F5427999B8D1A3F9CD1128FC69F4D75B434216810FA367E98

-- Chaining: the BINARY output of one hmac feeds in as the key of the next.
> SELECT hex(hmac(hmac('key', 'message'), 'message2'));
28042756E0362D954B61661BB4DEC9FF9F6C970D346CAEB6DB36ED7B735AB38C

-- A NULL argument yields NULL.
> SELECT hmac(CAST(NULL AS BINARY), 'message');
NULL

-- An unsupported algorithm raises an error.
> SELECT hmac('key', 'message', 'SHA-3');
Error: INVALID_PARAMETER_VALUE.HMAC_ALGORITHM

-- An empty key raises an error.
> SELECT hmac('', 'message');
Error: INVALID_PARAMETER_VALUE.HMAC_CRYPTO_ERROR