2013-06-20 54 views
2

我的同事有一個存儲帳戶信息的數據庫;一個賬戶的SHA256散列密碼和鹽值作爲原始二進制數據(blob)存儲在列中。什麼是Node.js相當於PHP哈希函數(包括鹽和原始輸出)?

密碼使用這個(true表示原始輸出)在PHP散列:

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; 
} 

回答

3

經過大量的實驗,我找到了一個解決方案。

/** 
* 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,但他讓我走上了正確的道路。

+1

請**不要**使用SHA哈希來存儲密碼。你應該使用專門爲密碼設計的東西,如[bcrypt](http://codetheory.in/using-the-node-js-bcrypt-module-to-hash-and-safely-store-passwords/)。每秒可燒錄數十億SHA256編碼密碼。鹽分幫助,但比你想象的要少很多。如果您正在使用現有的PHP應用程序,您會遇到困難,但即使PHP支持bcrypt。 – tadman

+0

這不是我的選擇,現在改變它爲時已晚。 PHP已經由其他人撰寫並且非常龐大。 – afollestad