HMAC signing
Each signed callback includes two extra HTTP headers:| Header | Description |
|---|---|
X-Timestamp | Unix epoch seconds at the time the request was sent |
X-Signature | HMAC-SHA256 signature in the format sha256=<base64-encoded-value> |
How the signature is computed
The signature is computed over the timestamp and the raw request body: HMAC-SHA256(api_client_secret, "{X-Timestamp}.{body}")body is the exact JSON string of the request body. Do not reformat or change whitespace.
Verify the signature
1
Read the headers
Extract the
X-Timestamp and X-Signature headers from the incoming request.2
Check the timestamp
Reject the request if
X-Timestamp is more than 5 minutes off from your clock. That limits replay of a captured request.3
Recompute the signature
Using your API client secret (UTF-8 encoded), compute:Use the raw request body bytes. Do not parse and re-serialize the JSON.
HMAC-SHA256("{X-Timestamp}.{raw request body}")
4
Compare
Base64-encode your computed HMAC, then compare it against the value in
X-Signature after stripping the sha256= prefix. If they match, handle the receipt. If they don’t, reject it with 401 Unauthorized.After you regenerate your API client secret, signed callbacks may still use
the previous secret for up to 5 minutes. During that window, verify against
both secrets.
Code examples
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import java.util.Base64
import scala.util.Try
def verifyCallback(
apiClientSecret: String,
timestampHeader: String,
signatureHeader: String,
rawBody: String
): Boolean = {
// Compute HMAC-SHA256 over an arbitrary payload
def hmac(payload: String): String = {
val mac = Mac.getInstance("HmacSHA256")
mac.init(new SecretKeySpec(apiClientSecret.getBytes("UTF-8"), "HmacSHA256"))
Base64.getEncoder.encodeToString(
mac.doFinal(payload.getBytes("UTF-8"))
)
}
Try {
val timestamp = timestampHeader.toLong
val now = System.currentTimeMillis() / 1000L
val isFresh = math.abs(now - timestamp) <= 300 // reject requests older / newer than 5 min
val expected = hmac(s"$timestampHeader.$rawBody") // sign "{timestamp}.{body}"
val received = signatureHeader.stripPrefix("sha256=")
isFresh && expected == received
}.getOrElse(false)
}
import * as crypto from "crypto";
const verifyCallback = (
apiClientSecret: string,
timestampHeader: string,
signatureHeader: string,
rawBody: string,
): boolean => {
// Reject requests whose timestamp is more than 5 minutes old or in the future
const isFresh = (ts: string): boolean => {
const t = parseInt(ts, 10);
return !isNaN(t) && Math.abs(Math.floor(Date.now() / 1000) - t) <= 300;
};
// Sign an arbitrary payload string with the API client secret
const computeHmac = (payload: string): string =>
crypto
.createHmac("sha256", apiClientSecret)
.update(payload, "utf8")
.digest("base64");
// Use a constant-time comparison to prevent timing attacks
const timingSafeEqual = (a: string, b: string): boolean =>
a.length === b.length &&
crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
return (
isFresh(timestampHeader) &&
timingSafeEqual(
computeHmac(`${timestampHeader}.${rawBody}`), // sign "{timestamp}.{body}"
signatureHeader.replace(/^sha256=/, ""), // strip the "sha256=" prefix
)
);
};
import hmac
import hashlib
import base64
import time
def verify_callback(
api_client_secret: str,
timestamp_header: str,
signature_header: str,
raw_body: str,
) -> bool:
# Reject requests whose timestamp is more than 5 minutes old or in the future
def is_fresh(ts: str) -> bool:
try:
return abs(time.time() - int(ts)) <= 300
except ValueError:
return False
# Sign an arbitrary payload string with the API client secret
def compute_hmac(payload: str) -> str:
return base64.b64encode(
hmac.new(
api_client_secret.encode("utf-8"),
payload.encode("utf-8"),
hashlib.sha256,
).digest()
).decode()
# compare_digest provides a constant-time comparison to prevent timing attacks
return is_fresh(timestamp_header) and hmac.compare_digest(
compute_hmac(f"{timestamp_header}.{raw_body}"), # sign "{timestamp}.{body}"
signature_header.removeprefix("sha256="), # strip the "sha256=" prefix
)
function verifyCallback(
string $apiClientSecret,
string $timestampHeader,
string $signatureHeader,
string $rawBody
): bool {
// Reject requests whose timestamp is more than 5 minutes old or in the future
$isFresh = static fn(string $ts): bool =>
abs(time() - (int) $ts) <= 300;
// Sign an arbitrary payload string with the API client secret
$computeHmac = static fn(string $payload): string =>
base64_encode(hash_hmac('sha256', $payload, $apiClientSecret, true));
// hash_equals provides a constant-time comparison to prevent timing attacks
return $isFresh($timestampHeader) && hash_equals(
$computeHmac("{$timestampHeader}.{$rawBody}"), // sign "{timestamp}.{body}"
preg_replace('/^sha256=/', '', $signatureHeader) // strip the "sha256=" prefix
);
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Optional;
import java.util.function.Function;
import java.nio.charset.StandardCharsets;
public boolean verifyCallback(
String apiClientSecret,
String timestampHeader,
String signatureHeader,
String rawBody
) {
// Sign an arbitrary payload string with the API client secret
Function<String, String> computeHmac = payload -> {
try {
var mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(
apiClientSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"
));
return Base64.getEncoder().encodeToString(
mac.doFinal(payload.getBytes(StandardCharsets.UTF_8))
);
} catch (Exception e) {
return "";
}
};
try {
return Optional.of(Long.parseLong(timestampHeader))
.filter(ts -> Math.abs(System.currentTimeMillis() / 1000L - ts) <= 300) // 5-min window
.map(__ -> computeHmac.apply(timestampHeader + "." + rawBody)) // sign "{timestamp}.{body}"
.map(expected -> expected.equals(signatureHeader.replaceFirst("^sha256=", ""))) // strip prefix & compare
.orElse(false);
} catch (NumberFormatException e) {
// Malformed timestamp header — reject the request
return false;
}
}
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"math"
"strconv"
"strings"
"time"
)
func verifyCallback(
apiClientSecret, timestampHeader, signatureHeader, rawBody string,
) bool {
// Reject requests whose timestamp is more than 5 minutes old or in the future
isFresh := func(ts string) bool {
timestamp, err := strconv.ParseInt(ts, 10, 64)
return err == nil && math.Abs(float64(time.Now().Unix()-timestamp)) <= 300
}
// Sign an arbitrary payload string with the API client secret
computeHmac := func(payload string) string {
mac := hmac.New(sha256.New, []byte(apiClientSecret))
mac.Write([]byte(payload))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
// hmac.Equal provides a constant-time comparison to prevent timing attacks
return isFresh(timestampHeader) && hmac.Equal(
[]byte(computeHmac(timestampHeader+"."+rawBody)), // sign "{timestamp}.{body}"
[]byte(strings.TrimPrefix(signatureHeader, "sha256=")), // strip the "sha256=" prefix
)
}
defmodule CallbackVerifier do
@max_age_seconds 300
def verify_callback(api_client_secret, timestamp_header, signature_header, raw_body) do
with {timestamp, _} <- Integer.parse(timestamp_header),
true <- fresh?(timestamp) do
# Build the signed payload, compute its HMAC, then compare using a
# constant-time function to prevent timing attacks
"#{timestamp_header}.#{raw_body}"
|> compute_hmac(api_client_secret)
|> Plug.Crypto.secure_compare(String.replace_prefix(signature_header, "sha256=", ""))
else
_ -> false
end
end
# Returns true when the timestamp is within the allowed 5-minute tolerance window
defp fresh?(timestamp),
do: abs(System.os_time(:second) - timestamp) <= @max_age_seconds
# Signs a payload with the given secret
defp compute_hmac(payload, secret),
do: :crypto.mac(:hmac, :sha256, secret, payload) |> Base.encode64()
end
module CallbackVerifier (verifyCallback) where
import Control.Monad (guard)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Maybe (MaybeT (..), runMaybeT)
import Crypto.Hash.Algorithms (SHA256)
import Crypto.MAC.HMAC (HMAC, hmac)
import Data.ByteArray.Encoding (Base (Base64), convertToBase)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
import Data.Maybe (isJust)
import Data.Time.Clock.POSIX (getPOSIXTime)
verifyCallback
:: ByteString -- ^ API client secret
-> ByteString -- ^ X-Timestamp header value
-> ByteString -- ^ X-Signature header value
-> ByteString -- ^ Raw request body
-> IO Bool
verifyCallback apiClientSecret timestampHeader signatureHeader rawBody =
-- runMaybeT turns any failed `guard` into Nothing; isJust maps that to Bool
isJust <$> runMaybeT (do
now <- liftIO $ round <$> getPOSIXTime
let timestamp = read (BC.unpack timestampHeader) :: Int
-- Reject requests more than 5 minutes old or in the future
guard $ abs (now - timestamp) <= 300
let expected = convertToBase Base64
(hmac apiClientSecret (timestampHeader <> "." <> rawBody) :: HMAC SHA256)
received = BC.drop 7 signatureHeader -- strip the "sha256=" prefix
-- guard short-circuits to Nothing (→ False) when signatures do not match
guard $ expected == received)
Compare signatures with a timing-safe function such as
crypto.timingSafeEqual, hmac.compare_digest, or hash_equals. Ordinary
string equality can leak whether the first bytes matched.IP whitelisting
You can reject requests that do not come from these addresses, at the network or in your handler. The same IPs send USSD callbacks.| IP Address | Role | Location |
|---|---|---|
88.99.209.40 | Primary | Falkenstein, Saxony, Germany |
94.130.34.45 | Failover | Falkenstein, Saxony, Germany |