首先,我阅读了这篇文章Hashing a password using SHA256 and .NET/Node.js,但对我没有帮助。
我需要在node.js环境中验证在ASP.NET中创建的密码哈希值。我被告知密码是使用此算法生成的:What is default hash algorithm that ASP.NET membership uses?。
我有一个示例密码哈希值和salt(第一行是密码,第二行是salt):
在C#中,
我需要用Node.js编写代码,该代码应返回与C#中的代码相同的值。有什么想法吗?
我需要在node.js环境中验证在ASP.NET中创建的密码哈希值。我被告知密码是使用此算法生成的:What is default hash algorithm that ASP.NET membership uses?。
我有一个示例密码哈希值和salt(第一行是密码,第二行是salt):
"Password": "jj/rf7OxXM263rPgvLan4M6Is7o=",
"PasswordSalt": "/Eju9rmaJp03e3+z1v5s+A==",
我知道哈希算法是SHA1
,也知道上面的哈希是为输入test123
生成的。但是我无法复现这个输入的相同哈希值。我尝试了以下方法:
Password = "jj/rf7OxXM263rPgvLan4M6Is7o="
PasswordSalt = "/Eju9rmaJp03e3+z1v5s+A=="
crypto = require("crypto")
sha1 = crypto.createHash("sha1")
PasswordSalt = new Buffer(PasswordSalt, 'base64').toString('utf8')
sha1.update(PasswordSalt+"test123", "utf8")
result = sha1.digest("base64")
console.log(Password)
console.log(result)
结果是:
jj/rf7OxXM263rPgvLan4M6Is7o=
xIjxRod4+HVYzlHZ9xomGGGY6d8=
我能够编写工作的C#算法:
using System.IO;
using System;
using System.Text;
using System.Security.Cryptography;
class Program
{
static string EncodePassword(string pass, string salt)
{
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Convert.FromBase64String(salt);
byte[] dst = new byte[src.Length + bytes.Length];
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inArray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
static void Main()
{
string pass = "test123";
string salt = "/Eju9rmaJp03e3+z1v5s+A==";
string hash = Program.EncodePassword(pass,salt);
Console.WriteLine(hash);
// outputs jj/rf7OxXM263rPgvLan4M6Is7o=
}
}
现在的问题只是将这个算法移植到node.js。问题在于c#似乎以某种神奇的方式操作字节,而我不知道如何在node中实现它。请考虑以下代码(它不使用任何盐值-仅从密码创建base64 sha1):
crypto = require("crypto")
pass = 'test123'
sha1 = crypto.createHash("sha1")
buf = new Buffer( pass, 'utf8')
sha1.update(buf)
result = sha1.digest("base64")
console.log(result)
// outputs cojt0Pw//L6ToM8G41aOKFIWh7w=
在C#中,
using System.Text;
using System.Security.Cryptography;
string pass = "test123";
byte[] bytes = Encoding.Unicode.GetBytes(pass);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inArray = algorithm.ComputeHash(bytes);
string hash = Convert.ToBase64String(inArray);
Console.WriteLine(hash);
// outputs Oc/baVMs/zM28IqDqsQlJPQc1uk=
我需要用Node.js编写代码,该代码应返回与C#中的代码相同的值。有什么想法吗?