我也有与原始海报相同的问题,我环顾四周并尝试不同的事情来理解机制。正如其他人已经指出的那样,盐被连接到最终的哈希值。所以这意味着几件事:
- 算法必须知道盐的长度
- 还必须知道盐在最终字符串中的位置。例如,如果从左侧或右侧偏移特定数字。
这两件事通常在实现中被硬编码,例如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');
}
});
}