Validating the Signature

To validate the signature, you can use this sample Java code. Make sure to perform JSON escaping on the payload received at the target.

This code includes the payload, signature received, and secret key. You can have similar code in your respective programming language.

1public static final String SIGNING_KEY_ALGO = "HMACSHA256";
2public static boolean isSignatureValid(String payload, String receivedSignature, String signingKey) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
3     Mac mac = Mac.getInstance(SIGNING_KEY_ALGO);
4     SecretKeySpec secretKeySpec =
5             new SecretKeySpec(
6                     signingKey.getBytes(StandardCharsets.UTF_8), SIGNING_KEY_ALGO);
7     mac.init(secretKeySpec);
8
9     String signature =
10             org.apache.commons.codec.binary.Base64.encodeBase64String(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
11     if(signature.equals(receivedSignature))
12     {
13         return true;
14     }
15     return false;
16}
1import hmac
2import hashlib
3import base64
4def is_signature_valid(payload: str, received_signature: str, signing_key: str) -> bool:
5    # Create a new HMAC-SHA256 object using UTF-8 bytes of the key
6    mac = hmac.new(signing_key.encode('utf-8'), digestmod=hashlib.sha256)
7    # Feed in the UTF-8 bytes of the payload
8    mac.update(payload.encode('utf-8'))
9    # Base64-encode the resulting HMAC digest and decode back to a string
10    computed_signature = base64.b64encode(mac.digest()).decode('utf-8')
11    return hmac.compare_digest(computed_signature, received_signature)