19

Im Storing SHA256 hashes of user passwords in my database generated by .NET and I need to be able to check them with Node.js. The only problem is that .NET and Node.js create different hashes for the same password.

Password: ThisPassword  

.NET:

var ue = new UnicodeEncoding();  
var byteSourceText = ue.GetBytes("ThisPassword");  
var byteHash = new System.Security.Cryptography.SHA256Managed().ComputeHash(byteSourceText);  
return Convert.ToBase64String(byteHash);

//Tlwxyd7HIQhXkN6DrWJtmB9Ag2fz84P/QgMtbi9XS6Q=

Node.js (Using Crypto):

var crypto = require('crypto');
return crypto.createHash('sha256').update('ThisPassword').digest('base64')

//d7I986+YD1zS6Wz2XAcDv2K8yw3xIVUp7u/OZiDzhSY=

I found this, but was unable to figure out how to implement his solution.

Community
  • 1
  • 1
davey555
  • 720
  • 1
  • 7
  • 15

3 Answers3

32

Edit: You are using UTF-16 in C#, you must use same encoding in both languages:

Node.js:

var crypto = require("crypto");
var sha256 = crypto.createHash("sha256");
sha256.update("ThisPassword", "utf8");//utf8 here
var result = sha256.digest("base64");
console.log(result); //d7I986+YD1zS6Wz2XAcDv2K8yw3xIVUp7u/OZiDzhSY=

C#:

SHA256 sha256 = SHA256Managed.Create(); //utf8 here as well
byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes("ThisPassword"));
string result = Convert.ToBase64String(bytes);
Console.WriteLine(result); //d7I986+YD1zS6Wz2XAcDv2K8yw3xIVUp7u/OZiDzhSY=
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • 1
    Thank you, this worked great! I was adding code when you answered. :) – davey555 Dec 05 '12 at 00:36
  • 2
    Ok, so the solution above changes the .NET implementation to match that of JS (ie. UTF-8). We have a similar situation except that we have stored hashes calculated with Unicode encoding (UTF-16). So the question is how to we change the JS implementation to match? – Jaans Jul 31 '13 at 02:58
1

If you're using the .NET Framework's built-in SqlMembershipProvider Class from System.Web.Security, the hash incorporates a salt value as well as the password material when it is generated. Simply hashing the password alone in your node.js will never produce the same result as the hash in the database.

See Microsoft ASP.NET 2.0 Providers: Introduction for a link to .NET source code for the provider that will let you see how the salt value is applied.

You need to include your code if you need more help than this.

JamieSee
  • 12,696
  • 2
  • 31
  • 47
0

I created the node pbkdf2 module(source https://github.com/fundon/pbkdf2)

Required node >= 0.11.11

var pbkdf2 = require('pbkdf2');
var p = 'password';
var s = pbkdf2.generateSaltSync(32);
var pwd = pbkdf2.hashSync(p, s, 1, 20, 'sha256');
var bool = pbkdf2.compareSync(pwd, p, s, 1, 20, 'sha256');
fundon
  • 1,039
  • 2
  • 9
  • 6