TypeScript HMAC SHA1 验证方法

问题描述

我正在尝试编写一个 TypeScript 函数来验证哈希签名。这是如何在 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;
}

我的 TS 函数采用相同的参数,这是我迄今为止尝试过的

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();
}

我尝试过的方法都没有奏效。他们应该工作吗?是否是发送哈希的应用程序有问题?

如果没有,还有其他尝试的想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)