0

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 ?

bvdb
  • 22,839
  • 10
  • 110
  • 123
  • 1
    Unfortunately the same function is used for two different purposes, with the type of the `salt` parameter indicating which function is used. If salt is a number then a salt is automatically generated with that many characters. If it is a string then that string is used as the salt. The 2nd form might be used for comparing hashes, but the API already has a compare function so I see little need for the 2nd form. – President James K. Polk Sep 12 '20 at 14:23

1 Answers1

1

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)
Shaun the Sheep
  • 22,353
  • 1
  • 72
  • 100