我試圖使用NodeJS加密庫和C#Rfc2898DeriveBytes生成相同的密碼哈希。在使用NodeJ生成的鹽時,C#實現不會生成相同的密鑰。我究竟做錯了什麼?在C#和NodeJS中生成相同的PBKDF2鍵
的鹽和散列中的NodeJS生成:
Salt: GJNw/wzXZxEdXrheqo322mf0x+92AeAuAHH48iiGZ+A=
Hash: w6fCpsKxw78Fw4pMFk5Zw6vDin7CnG5VwpUWBSjCo8OSOTJ6w47Cv8KWcjIpwoA=
在C#生成的哈希:
1G84mPkY78nsQ2BzO/qUPd+e0Lobrz7ZLzc+p7Zh0o8=
我的C#測試代碼如下:
public const int HASH_BYTE_SIZE = 32;
public const int PBKDF2_ITERATIONS = 1000;
public static string HashPassword(string password, string salt)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] saltBytes = Convert.FromBase64String(salt);
var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, saltBytes, PBKDF2_ITERATIONS);
var hash = pbkdf2.GetBytes(HASH_BYTE_SIZE);
return Convert.ToBase64String(hash);
}
static void Main(string[] args)
{
string salt = "GJNw/wzXZxEdXrheqo322mf0x+92AeAuAHH48iiGZ+A=";
string plainTextPsw = "12345";
string hashedPsw = PasswordHash.HashPassword(plainTextPsw, salt);
Console.WriteLine(hashedPsw);
Console.ReadLine();
}
和的NodeJS:
var crypto = require('crypto');
var iterations = 1000;
var bytes = 32;
exports.createSalt = function() {
return new Buffer(crypto.randomBytes(bytes)).toString('base64');
}
exports.hash = function hash(text, salt, callback) {
crypto.pbkdf2(text, salt, iterations, bytes, function (err, derivedKey) {
if (err) { callback(err); }
else {
var h = new Buffer(derivedKey).toString('base64');
callback(null, h);
}
});
}
包含C#版本的結果。 – erickson 2015-02-11 00:29:41
當然,C#生成:1G84mPkY78nsQ2BzO/qUPd + e0Lobrz7ZLzc + p7Zh0o8 = – squiso 2015-02-11 06:56:13
請參閱我的解決方案的更新答案。 – erickson 2015-02-11 18:59:50