简体   繁体   中英

bcryptjs salt as a string

In the bcryptjs package there is a hash(s,salt) method.

/**
 * 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>;

Using a numeric salt parameter makes sense, but what happens if the salt is a string ? Can I just use any random string here ?

If you look at the example in the package docs , the salt string is a value returned by the function genSalt . You can't use a random string (try it and see, you'll get an exception).

The number isn't the length of the string, it is the cost factor for the hash function - incrementing it by one will double the time taken to calculate the hash.

Some examples to illustrate:

> 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM