[英]What's the Node.js equivelent of the PHP hash function (including salt and raw output)?
我的同事有一個存儲帳戶信息的數據庫; 帳戶的SHA256哈希密碼和鹽值作為原始二進制數據(blob)存儲在列中。
使用以下命令在PHP中對密碼進行哈希處理(true表示原始輸出):
hash("sha256", $salt . $password, true);
我正在嘗試在Node.js服務器上實施身份驗證,該服務器必須從PHP取回存儲在數據庫中的相同哈希密碼,但這似乎不起作用:
/**
* Validates a password sent by an end user by comparing it to the
* hashed password stored in the database. Uses the Node.js crypto library.
*
* @param password The password sent by the end user.
* @param dbPassword The hashed password stored in the database.
* @param dbSalt The encryption salt stored in the database.
*/
function validatePassword(password, dbPassword, dbSalt) {
// Should the dbSalt be a Buffer, hex, base64, or what?
var hmac = crypto.createHmac("SHA256", dbSalt);
var hashed = hmac.update(password).digest('base64');
console.log("Hashed user password: " + hashed);
console.log("Database password: " + dbPassword.toString('base64'));
return hashed === dbPassword;
}
經過大量的實驗,我找到了解決方案。
/**
* Encrypts a password using sha256 and a salt value.
*
* @param password The password to hash.
* @param salt The salt value to hash with.
*/
function SHA256Encrypt(password, salt) {
var saltedpassword = salt + password;
var sha256 = crypto.createHash('sha256');
sha256.update(saltedpassword);
return sha256.digest('base64');
}
/**
* Validates a password sent by an end user by comparing it to the
* hashed password stored in the database.
*
* @param password The password sent by the end user.
* @param dbPassword The hashed password stored in the database, encoded in Base64.
* @param dbSalt The encryption salt stored in the database. This should be a raw blob.
*/
function validatePassword(password, dbPassword, dbSalt) {
var hashed = SHA256Encrypt(password, dbSalt.toString('binary'));
return hashed === dbPassword;
}
不過,由於TravisO,他使我走上了正確的道路。
crypto.createHash()
http://nodejs.org/docs/v0.6.18/api/crypto.html#crypto_crypto_createhash_algorithm
只要絕對確保使用完全相同的哈希類型和鹽即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.