jthomas
jthomas

Reputation: 65

TypeScript HMAC SHA1 Verification Method

I am trying to write a TypeScript function to verify a hash signature. Here is an example of how this is done in C#

private bool Verify(string hash, string body, string key)
{
    var keyBytes = Encoding.UTF8.GetBytes(key);
    var bodyBytes = Encoding.UTF8.GetBytes(body);

    var hmac = new HMACSHA1(keyBytes);
    var result = hmac.ComputeHash(bodyBytes);
    var cleanedResult = BitConverter.ToString(result).Replace("-", "");
    return cleanedResult == hash;
}

My TS function takes in the same parameters, and here's what I've tried so far

const validateSignature = (hash: string, body: string, key: string): boolean => {
  console.log(`hash: ${hash.toLowerCase()}`);

  // doesn't match
  let resultKeyBody = CryptoJS.HmacSHA1(CryptoJS.enc.Utf8.parse(JSON.stringify(key)), CryptoJS.enc.Utf8.parse(body));
  console.log(`resultKeyBody: ${resultKeyBody}`);

  // doesn't match
  let resultBodyKey = CryptoJS.HmacSHA1(CryptoJS.enc.Utf8.parse(JSON.stringify(body)), CryptoJS.enc.Utf8.parse(key));
  console.log(`resultBodyKey: ${resultBodyKey}`);

  // doesn't match
  let otherResultBodyKey = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(CryptoJS.enc.Utf8.parse(body), CryptoJS.enc.Base64.parse(key)));
  console.log(`otherResultBodyKey: ${otherResultBodyKey}`);
  
  // this one below was throwing an error
  //let otherResultKeyBody = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(CryptoJS.enc.Utf8.parse(key), CryptoJS.enc.Base64.parse(body)));
  //console.log(`otherResultKeyBody: ${otherResultKeyBody}`);

  return resultKeyBody?.toString().toLowerCase() === hash.toLowerCase();
}

None of the ways I've tried to do it have worked. Should they work? Could it be a problem with the application that is sending the hash?

If not, any other ideas for something to try?

Upvotes: 1

Views: 892

Answers (0)

Related Questions