-1

I use some remote api, they use such C# code:

SHA256Managed sha256Managed = new SHA256Managed();
byte[] passwordSaltBytes = Encoding.Unicode.GetBytes("zda");

byte[] hash = sha256Managed.ComputeHash(passwordSaltBytes);

string result = Convert.ToBase64String(hash);

Console.WriteLine("result = " + result); // result = NUbWRkT8QfzmDt/2kWaikNOZUXIDt7KKRghv0rTGIp4=

I need to get the same result in my javascript frontend code. Does somebody can help with such problem?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • You might want to explore some Javascript libraries to achieve this easily. Check this post out: https://stackoverflow.com/questions/18338890/are-there-any-sha-256-javascript-implementations-that-are-generally-considered-t – lloydaf Dec 03 '18 at 12:45
  • Not sure why you are hashing on the front end side though. Not safe right? – lloydaf Dec 03 '18 at 12:46
  • @theapologist i read this https://stackoverflow.com/questions/18338890/are-there-any-sha-256-javascript-implementations-that-are-generally-considered-t and try to use some libe like js-sha256 and crypto-js but I could not find the right combination of actions to repeat the С# result, maybe you can help me =) – Олег Якубсон Dec 03 '18 at 12:51

2 Answers2

0

The answer is:

var utf8arr = CryptoJS.enc.Utf16LE.parse("zda");
var hash = CryptoJS.SHA256(utf8arr);
var base64 = CryptoJS.enc.Base64.stringify(hash);
console.log(base64);
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
0

Not quite obvious, but Unicode in C# is using UTF-16LE enconding.

So you can use CryptoJS to achieve the same result:

var utf16 = CryptoJS.enc.Utf16LE.parse("zda");
var hash = CryptoJS.SHA256(utf16);
var base64 = CryptoJS.enc.Base64.stringify(hash);
console.log(base64);
affaron
  • 1
  • 1
  • 1