代码之家  ›  专栏  ›  技术社区  ›  bvdb

bcryptjs盐作为字符串

  •  0
  • bvdb  · 技术社区  · 5 年前

    在the 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 ? 我可以在这里使用任何随机字符串吗?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Shaun the Sheep    5 年前

    如果你看看这个例子 in the package docs ,salt字符串是函数返回的值 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)
    
    推荐文章