Skip to main content

Sample Code

Java

public class WebhookSignatureValidator {
    public boolean validateSignature(String body,
                                     String signature,
                                     String secretKey,
                                     String timestamp) throws NoSuchAlgorithmException, InvalidKeyException {

        // Create the message to be signed by concatenating the message body and the timestamp
        var message = body + timestamp;

        // Initialize the MAC routine with the secret key
        var mac = Mac.getInstance("HmacSHA256");
        var secret = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(secret);
        
        // Create a digest of the bytes in the message
        byte[] digest = mac.doFinal(message.getBytes());

        // Print the digest as lower-case hex characters
        var enc = DatatypeConverter.printHexBinary(digest).toLowerCase();
        
        return signature.equals(enc);
    }
}