问题描述
在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)
'$2a$12$MDnofLJT8LrIILyh8SCle.'
> bcrypt.genSaltSync(14)
'$2a$14$fuc6ZCGfcUmsG.GiUYmdGe'
> bcrypt.hashSync("password",bcrypt.genSaltSync(12))
'$2a$12$NowrlsgseFUgTxlAUZ3jw.uZyf2uuZkeaoZU0r997DLd00/y0yp6e'
> bcrypt.hashSync("password",bcrypt.genSaltSync(15))
'$2a$15$xOjjGl6f60A3zUck6HhSEu/UcLLG//EkbDTKl6GFy3jNTgT..kQPC'
> bcrypt.hashSync("password",12)
'$2a$12$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)