简体   繁体   中英

Code example for C# and Javascript SHA256 hashing

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.

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

检查以下URL上的Java脚本SHA256实现http://www.movable-type.co.uk/scripts/sha256.html

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