我也有与原始海报相同的问题,它看起来有点环顾四周,并尝试了不同的方法来理解该机制。正如其他人已经指出的那样,盐被连接到最终的哈希表中。因此,这意味着两件事:
- 该算法必须知道盐的长度
- 还必须知道盐在最终字符串中的位置。例如,如果从左侧或右侧偏移了特定数字。
这两件事通常在实现中进行硬编码,例如bcryptjs的bcrypt实现源将盐长度定义为16
/**
* @type {number}
* @const
* @private
*/
var BCRYPT_SALT_LEN = 16;
因此,为了说明该想法背后的基本概念,如果有人想手动进行操作,它将类似于以下内容。如果有可以使用的库,我不建议您自己实现这样的事情。
var salt_length = 16;
var salt_offset = 0;
var genSalt = function(callback)
{
var alphaNum = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ';
var salt = '';
for (var i = 0; i < salt_length; i++) {
var j = Math.floor(Math.random() * alphaNum.length);
salt += alphaNum[j];
}
callback(salt);
}
// cryptographic hash function of your choice e.g. shar2
// preferably included from an External Library (dont reinvent the wheel)
var shar2 = function(str) {
// shar2 logic here
// return hashed string;
}
var hash = function(passwordText, callback)
{
var passwordHash = null;
genSalt(function(salt){
passwordHash = salt + shar2(passwordText + salt);
});
callback(null, passwordHash);
}
var compare = function(passwordText, passwordHash, callback)
{
var salt = passwordHash.substr(salt_offset, salt_length);
validatedHash = salt + shar2(passwordText + salt);
callback(passwordHash === validatedHash);
}
// sample usage
var encryptPassword = function(user)
{
// user is an object with fields like username, pass, email
hash(user.pass, function(err, passwordHash){
// use the hashed password here
user.pass = passwordHash;
});
return user;
}
var checkPassword = function(passwordText, user)
{
// user has been returned from database with a hashed password
compare(passwordText, user.pass, function(result){
// result will be true if the two are equal
if (result){
// succeeded
console.log('Correct Password');
}
else {
// failed
console.log('Incorrect Password');
}
});
}