# hmac\_sha256

Generates an HMAC-SHA256 hash of a message using a secret key. Commonly used for webhook signature verification, API authentication, and secure token generation.

```liquid
{% assign signature = "message body" | hmac_sha256: "secret_key" %}
{% log signature %}
```

#### Syntax

```liquid
{{ message | hmac_sha256: key }}
{{ message | hmac_sha256: key, encoding }}
```

| Parameter  | Description                                                 |
| ---------- | ----------------------------------------------------------- |
| `message`  | The string to hash                                          |
| `key`      | The secret key used for hashing                             |
| `encoding` | Output encoding: `"hex"` (default), `"base64"`, or `"utf8"` |

#### Return Value

Returns the HMAC-SHA256 hash as a string in the specified encoding.

#### Examples

**Generate a hex-encoded signature (default):**

```liquid
{% assign signature = request.body | hmac_sha256: "my_secret" %}
{% log signature %}
```

Output:

```
a1b2c3d4e5f6...
```

**Generate a base64-encoded signature:**

```liquid
{% assign signature = request.body | hmac_sha256: "my_secret", "base64" %}
{% log signature %}
```

**Verify a Shopify webhook signature:**

```liquid
{% assign computed = request.raw_body | hmac_sha256: SHOPIFY_WEBHOOK_SECRET, "base64" %}
{% if computed == request.headers["X-Shopify-Hmac-SHA256"] %}
  {% log "Webhook signature valid" %}
{% else %}
  {% log "Invalid webhook signature!" %}
{% endif %}
```

**Sign an API request:**

```liquid
{% capture string_to_sign %}{{ timestamp }}{{ request_body }}{% endcapture %}
{% assign signature = string_to_sign | hmac_sha256: API_SECRET_KEY %}

{% json headers %}
{
  "X-Signature": "{{ signature }}",
  "X-Timestamp": "{{ timestamp }}"
}
{% endjson %}
```

#### Notes

* Default encoding is `hex`
* Supported encodings: `hex`, `base64`, `utf8`
* The secret key should be stored in global variables, not hardcoded in scripts
* See also: `sha1`, `base64_encode`
