bcryptjs 盐作为字符串

bcryptjs salt as a string

bcryptjs 包中有一个 hash(s,salt) 方法。

/**
 * Asynchronously generates a hash for the given string.
 * @param s                String to hash
 * @param salt             Salt length to generate or salt to use
 * @return Promise with resulting hash, if callback has been omitted
 */
export declare function hash(s: string, salt: number | string): Promise<string>;

使用数字 salt 参数是有意义的,但是如果盐是 string 会怎样? 我可以在这里使用任何随机字符串吗?

如果您查看示例 in the package docs,盐字符串是函数 genSalt 返回的值。您不能使用随机字符串(试试看,您会得到一个例外)。

该数字不是字符串的长度,它是散列函数的成本因子 - 将它递增 1 将使计算散列所需的时间加倍。

举例说明:

> var bcrypt = require('bcryptjs');
undefined
> bcrypt.genSaltSync(12)
'a$MDnofLJT8LrIILyh8SCle.'
> bcrypt.genSaltSync(14)
'a$fuc6ZCGfcUmsG.GiUYmdGe'
> bcrypt.hashSync("password", bcrypt.genSaltSync(12))
'a$NowrlsgseFUgTxlAUZ3jw.uZyf2uuZkeaoZU0r997DLd00/y0yp6e'
> bcrypt.hashSync("password", bcrypt.genSaltSync(15))
'a$xOjjGl6f60A3zUck6HhSEu/UcLLG//EkbDTKl6GFy3jNTgT..kQPC'
> bcrypt.hashSync("password", 12)
'a$Ks072IiTxgBYG9atJYeHCu7QpnIOylp/VjQmV6vW4mKRh43hYxkcO'
> bcrypt.hashSync("password", "invalid")
Uncaught Error: Invalid salt version: in
    at _hash (/home/blah/blah/node_modules/bcryptjs/dist/bcrypt.js:1280:19)
    at Object.bcrypt.hashSync (/home/blah/blah/node_modules/bcryptjs/dist/bcrypt.js:190:16)