简体   繁体   English

C#和Javascript SHA256散列的代码示例

[英]Code example for C# and Javascript SHA256 hashing

I have an algorithm in C# running on server side which hashes a base64-encoded string. 我在服务器端运行的C#中有一个算法,它会散列一个base64编码的字符串。

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. 我喜欢用javascript实现相同的功能,使用serverSalt,因为它是通过websocket从C#传输的。

I know SHA-256 hashes different between C# and Javascript because C# and Javascript have different string encodings. 我知道在C#和Javascript之间有不同的SHA-256哈希,因为C#和Javascript有不同的字符串编码。 But I know I can pad zeros in the byte array to make Javascript behave as C# (step 1 above is solved). 但我知道我可以在字节数组中填充零以使Javascript表现为C#(上面的步骤1已经解决)。

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? 任何人都可以提供一些有关我可以用来重现步骤2,3和4的算法的见解吗?

PS: there are already questions and answers around but not a single code snippet. PS:已经有问题和答案,但没有一个代码片段。

Here's the solution, I really hope this could help other people in the same situation. 这是解决方案,我真的希望这可以帮助处于相同情况的其他人。

In the html file, load crypto-js library 在html文件中,加载crypto-js库

<!-- 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 在javascript中,执行以下操作

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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