简体   繁体   中英

HMAC256 from C# to Javascript returns different results

I want to create a HMAC256 key from a string with a HMAC key based on my C# project in Javascript. however, each project has different results and can't seem to find a way to make the results identical.

C# PROJECT

private string CalculateHMAC(string hmacKey, string signingstring) {
  byte[] key = PackH(hmacKey) //returns 32 bit array;
  byte[] data = Encoding.UTF8.GetBytes(signingstring);

  try {
    using(HMACSHA256 hmac = new HMACSHA256(key)) {
      // Compute the hmac on input data bytes
      byte[] rawHmac = hmac.ComputeHash(data);

      // Base64-encode the hmac
      return Convert.ToBase64String(rawHmac);
    }
  } catch (Exception e) {
    throw new Exception("Failed to generate HMAC : " + e.Message);
  }
}

JAVASCRIPT CODE

var hash = CryptoJS.HmacSHA256(byteString, hmacKeyinString);
var msg = hash.toString(CryptoJS.enc.Base64);

Thank you in advance.

Using CryptoJS in my javascript project

fixed with this line of code

        var wordsKey = CryptoJS.enc.Hex.parse('yourkey');

        var hash = CryptoJS.HmacSHA256(convertString, wordsKey);
        var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM