Code example for C# and Javascript SHA256 hashing

左心房为你撑大大i 提交于 2019-12-10 10:04:14

问题


I have an algorithm in C# running on server side which hashes a base64-encoded string.

byte[] salt = Convert.FromBase64String(serverSalt); // Step 1
SHA256Managed sha256 = new SHA256Managed(); // Step 2
byte[] hash = sha256.ComputeHash(salt); // Step 3
Echo("String b64: " + Convert.ToBase64String(hash)); // Step 4

The hash is then checked against a database list of hashes. I'd love to achieve the same with javascript, using the serverSalt as it is transmitted from C# through a websocket.

I know SHA-256 hashes different between C# and Javascript because C# and Javascript have different string encodings. But I know I can pad zeros in the byte array to make Javascript behave as C# (step 1 above is solved).

var newSalt  = getByteArrayFromCSharpString(salt); // Pad zeros where needed
function getByteArrayFromCSharpString(inString)
{
  var bytes = [];
  for (var i = 0; i < inString.length; ++i)
{
    bytes.push(inString.charCodeAt(i));
    bytes.push(0);
}
return bytes;
}

Could anyone provide some insight on which algorithms I could use to reproduce steps 2, 3 and 4?

PS: there are already questions and answers around but not a single code snippet.


回答1:


Here's the solution, I really hope this could help other people in the same situation.

In the html file, load crypto-js library

<!-- library for doing password hashing, base64 eoncoding / decoding -->
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/core-min.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/sha256.js"></script>

In the javascript, do the following

// This function takes a base64 string, hashes it with the SHA256 algorithm
// and returns a base64 string. 
function hashBase64StringAndReturnBase64String(str)
{
    // Take the base64 string and parse it into a javascript variable
    var words  = CryptoJS.enc.Base64.parse(str);
    // Create the hash using the CryptoJS implementation of the SHA256 algorithm
    var hash = CryptoJS.SHA256(words);
    var outString =  hash.toString(CryptoJS.enc.Base64)
    // Display what you just got and return it
    console.log("Output string is: " + outString);
    return outString;
}



回答2:


check Java script SHA256 implementation on the following URL http://www.movable-type.co.uk/scripts/sha256.html



来源:https://stackoverflow.com/questions/13821003/code-example-for-c-sharp-and-javascript-sha256-hashing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!