Secure random token in Node.js

后端 未结 12 1029
盖世英雄少女心
盖世英雄少女心 2020-11-28 00:05

In this question Erik needs to generate a secure random token in Node.js. There\'s the method crypto.randomBytes that generates a random Buffer. However, the ba

12条回答
  •  不知归路
    2020-11-28 00:59

    The npm module anyid provides flexible API to generate various kinds of string ID / code.

    To generate random string in A-Za-z0-9 using 48 random bytes:

    const id = anyid().encode('Aa0').bits(48 * 8).random().id();
    // G4NtiI9OYbSgVl3EAkkoxHKyxBAWzcTI7aH13yIUNggIaNqPQoSS7SpcalIqX0qGZ
    

    To generate fixed length alphabet only string filled by random bytes:

    const id = anyid().encode('Aa').length(20).random().id();
    // qgQBBtDwGMuFHXeoVLpt
    

    Internally it uses crypto.randomBytes() to generate random.

提交回复
热议问题