Node.js
const crypto = require('crypto');
const isValidRequest = (body, requestHash, signingKey) => {
const computedHash = crypto.createHmac('sha256', signingKey)
.update(body)
.digest()
.toString('base64');
return requestHash === computedHash;
}
const body = 'webhook-request-raw-body';
const signingKey = 'speechlive-webhook-signing-key';
const requestHash = 'C9KrAVd/H/45J5mApsnTAfd50KvJ5b93Oe0bxBXXF4E=';
const isValidRequest = isValidRequest(body, requestHash, signingKey);
console.log('Is valid request: ', isValidRequest);
C#
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string body = "webhook-request-raw-body";
string signingKey = "speechlive-webhook-signing-key";
string requestHash = "C9KrAVd/H/45J5mApsnTAfd50KvJ5b93Oe0bxBXXF4E=";
bool isValidRequest = this.isValidRequest(body, requestHash, signingKey);
Console.WriteLine($"Is valid request: {isValidRequest}");
}
static bool isValidRequest(string body, string requestHash, string signingKey)
{
byte[] signingKeyBytes = Encoding.UTF8.GetBytes(signingKey);
using (var hmac= new HMACSHA256(signingKeyBytes))
{
byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
byte[] hashBytes = hmac.ComputeHash(bodyBytes);
string computedHash = Convert.ToBase64String(hashBytes);
Console.WriteLine($"Computed HMAC SHA 256 Hash: {computedHash}");
return computedHash == requestHash;
}
}
}