Base64, SHA-256, and HMAC Functions in HTTP Rule Expressions
How Cloudflare Rules language encode_base64, sha256, decode_base64, and is_timed_hmac_valid_v0 work, where each applies, and how signed URLs fit together.
This page summarizes Cloudflare Ruleset Engine documentation on cryptographic and collection helpers in the Rules language: encoding and decoding Base64, computing SHA-256 digests, validating timed HMAC tokens, and working with header maps and comma-separated lists. The same ideas appear in browser APIs (btoa / atob) and in origin code that signs URLs checked at the edge.
encode_base64 and decode_base64: what they do at the edge
Section titled “encode_base64 and decode_base64: what they do at the edge”encode_base64() turns a string or byte value into Base64 text inside a rule expression—useful when an origin or partner expects a Base64 signature or credential derived from request fields. decode_base64() does the reverse on a field (not a string literal), for example to compare a decoded header value.
Cloudflare documents the encoder as follows:
Encodes an input string or byte array to Base64 format.
— Cloudflare, Functions — encode base64
encode_base64 flags: standard, URL-safe, and padding
Section titled “encode_base64 flags: standard, URL-safe, and padding”| Flag | Effect |
|---|---|
| (default) | Standard Base64, no padding |
u |
URL-safe alphabet (- and _ instead of + and /) |
p |
Adds = padding so length is a multiple of 4 |
Examples from the rules changelog:
encode_base64("hello world")→aGVsbG8gd29ybGQencode_base64("hello world", "p")→aGVsbG8gd29ybGQ=encode_base64("hello world", "u")→aGVsbG8gd29ybGQ
You can chain encoding with request data, for example a canonical string plus a secret:
encode_base64(sha256(concat(to_string(ip.src), http.host, "my-secret")))Cache rule expressions also list decode_base64 among available functions for that phase.
sha256 in rule expressions: digests and signed headers
Section titled “sha256 in rule expressions: digests and signed headers”sha256(input) returns a 32-byte hash of a string or bytes. Typical uses include integrity checks, token material, and inputs to encode_base64() when a system expects a Base64-wrapped digest.
Computes the SHA-256 cryptographic hash of the input string or byte array. Returns a 32-byte hash value.
— Cloudflare, Functions — sha256
Changelog material describes the combined pattern:
Compute the SHA256 hash of a string and encode the result to Base64 format:
encode_base64(sha256("my-token"))— Combines hashing and encoding for systems that expect Base64-encoded signatures.— Cloudflare, New cryptographic functions — encode_base64() and sha256()
is_timed_hmac_valid_v0: validate signed URLs and query tokens
Section titled “is_timed_hmac_valid_v0: validate signed URLs and query tokens”For hash-based message authentication code (HMAC) tokens with an expiry, Cloudflare provides is_timed_hmac_valid_v0() in the Rules language. The WAF token authentication guide and HMAC validation describe the same flow: your origin (or a Workers sign-requests example) builds a MAC; a custom rule blocks traffic when validation fails.
Use the Rules language
is_timed_hmac_valid_v0()HMAC validation function to validate hash-based message authentication code (HMAC) tokens in a custom rule expression.— Cloudflare, Configure token authentication
Access requires Pro, Business, or Enterprise (HMAC validation note).
MessageMAC layout: message, separator, timestamp, mac
Section titled “MessageMAC layout: message, separator, timestamp, mac”A valid MessageMAC matches:
(.+)(.*)(\d{10})-(.{43,})| Part | Role | Example |
|---|---|---|
| Message | Path or payload to authenticate | /images/cat.jpg |
| Separator | Between message and timestamp (often ?verify=) |
?verify= |
| Timestamp | 10-digit UNIX seconds when MAC was issued | 1484063787 |
| mac | Base64 HMAC (often URL-encoded in the URI) | 9JQB8vP1z0yc5DEBnH6JGWM3mBmvIeMrnnxFi3WtJLE%3D |
When the whole token lives in one field (common for http.request.uri):
is_timed_hmac_valid_v0( "mysecrettoken", http.request.uri, 10800, http.request.timestamp.sec, 8)Here 8 is len("?verify=")—the separator length between message and timestamp (MessageMAC in a single field).
URL encoding vs URL-safe Base64 (flags s)
Section titled “URL encoding vs URL-safe Base64 (flags s)”When you do not use the optional flags argument for
is_timed_hmac_valid_v0(), you must URL encode the Base64-encoded MAC value.— Cloudflare, Configure token authentication
With flags set to 's', the function expects a URL-safe Base64 MAC without padding in MessageMAC. Without 's', URL-encode the MAC in the URI (Overview — flags).
Prefix paths and concat for custom MessageMAC
Section titled “Prefix paths and concat for custom MessageMAC”You can authenticate a fixed-length path prefix once for many files under that prefix by passing concat(substring(http.request.uri.path, 0, 51), "?", http.request.uri.query) as MessageMAC (protect an entire URI path prefix). Split fields use concat() as in the concatenated MessageMAC example.
The Sign requests snippet and Workers signing example use HMAC-SHA256 and Base64 in a way that is compatible with is_timed_hmac_valid_v0(), so you can sign at the edge and verify in a WAF custom rule without mismatched formats.
split, join, has_key, and has_value: lists and header maps
Section titled “split, join, has_key, and has_value: lists and header maps”Rulesets gained string and map helpers for expressions that inspect headers or allow-lists (array and map changelog):
| Function | Purpose |
|---|---|
split(source, delimiter, limit) |
Split a string into an array (limit is a literal 1–128) |
join(items, separator) |
Join array strings with a separator |
has_key(map, key) |
Test whether a map contains a key |
has_value(map, value) |
Test whether a map contains a value |
Example patterns from the changelog:
has_value(split(http.response.headers["x-allow-country"][0], ","), ip.src.country)— country in a comma-separated allow listhas_key(http.request.headers, "x-custom-header")— header presentjoin(http.request.headers.names, ", ")— single string of header names
In the Rules language, http.request.headers is a Map<Array<String>>; keys use bracket notation (Maps — Values). Use any(...[*] ...) when matching any element of a multi-value header (Arrays).
btoa and atob in browsers and Workers vs edge rule functions
Section titled “btoa and atob in browsers and Workers vs edge rule functions”In web platforms, Base64 helpers operate on Unicode strings representing byte values, not arbitrary binary buffers:
The
atob()andbtoa()methods allow developers to transform content to and from the base64 encoding.— WHATWG, 8.3 Base64 utility methods
Cloudflare Workers expose the same atob() / btoa() APIs. The Workers signing examples convert an ArrayBuffer signature to Base64 via btoa(String.fromCharCode(...)) before putting it in verify=. That is client/runtime encoding; encode_base64() is server-side rule evaluation on request fields, with explicit u / p flags and product-specific placement (header transforms only).
Common conclusion: Use btoa / atob (or your language’s HMAC library) when generating or parsing tokens in application code; use encode_base64 / decode_base64 / is_timed_hmac_valid_v0() when enforcing policy on traffic in Cloudflare rules. Align padding and URL-safe alphabet with the flags you pass to both the generator and is_timed_hmac_valid_v0().
Common mistakes when mixing Base64, SHA-256, and HMAC
Section titled “Common mistakes when mixing Base64, SHA-256, and HMAC”- Using
decode_base64("literal")—sourcemust be a field (decode base64). - Expecting
sha256()on all plans or in custom WAF expressions — Enterprise entitlement and Transform Rule rewrite scope only. - Forgetting URL-encoding of the MAC in
http.request.uriwhen not using flag's'. - Putting
verifybefore other query parameters — it must be last (token authentication). - Mismatching separator length:
lengthOfSeparatormust match the bytes between message and the 10-digit timestamp (for example8for?verify=). - Using
split()in a rule phase where the function is not supported (see split). - Reusing one HMAC for different messages — same secret can cover many paths, but each message needs its own token (several paths, same secret).
How to check this on your site
Section titled “How to check this on your site”- In the Cloudflare dashboard, open Security → WAF → Custom rules and add a test expression using
is_timed_hmac_valid_v0()as in Configure token authentication, then issue a request with and without a validverifyparameter. - Deploy a header transform rule that sets a test header to
encode_base64("hello world")and confirm the value matches the examples in encode_base64 changelog. - If entitled, test
encode_base64(sha256(...))in a Transform Rule rewrite and compare output with your origin’s digest (sha256). - Optionally run the Sign requests Worker against the same secret and TTL as your custom rule to confirm end-to-end compatibility.
- You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.