在这个问题中Erik需要在Node.js中生成一个安全的随机令牌。这是crypto方法。生成一个随机Buffer的randomBytes。但是,节点中的base64编码不是url安全的,它包含/和+而不是-和_。因此,我发现生成这种令牌的最简单方法是

require('crypto').randomBytes(48, function(ex, buf) {
    token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
});

还有更优雅的方式吗?


当前回答

随机URL和文件名字符串安全(1行)

Crypto.randomBytes(48).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');

其他回答

尝试crypto.randomBytes ():

require('crypto').randomBytes(48, function(err, buffer) {
  var token = buffer.toString('hex');
});

'hex'编码在节点v0.6中工作。X或更新版本。

从Node.js 14.18和15.7开始,内置了url安全的base64编码支持:

const token = crypto.randomBytes(48).toString('base64url');

如果你想使用异步版本(因为函数可能不得不等待熵),它可以被承诺更好地与现代模式对齐:

const randomBytesAsync = util.promisify(crypto.randomBytes);

const token = (await randomBytesAsync(48)).toString('base64url');

零依赖解决方案…适用于浏览器,deno和nodejs(新的全局web加密)

Const random = size => String.fromCharCode ( …crypto.getRandomValues ( 新Uint8Array(大小) ) ) ).replaceAll(“+”,“x”)。replaceAll(“/”,“我”)。片(0,大小) For(令I = 5;我——;)console.log(随机(16))

所有doe我只会使用一个uint8array \w预定义的长度,并称为crypto。getRandomValues每当我需要一些uniq(和切片如果我必须),从来不处理字符串或base64, base64只是不必要的开销。 (为fast分配大量缓冲区的成本很高)

const buf256 = new Uint8Array(256)
const random = crypto.getRandomValues.bind(crypto, buf256)

for (let i = 5; i--;) random()//.slice()

同步选项,以防万一,如果你不是一个JS专家像我。不得不花一些时间如何访问内联函数变量

var token = crypto.randomBytes(64).toString('hex');

Crypto-random-string是一个很好的模块。

const cryptoRandomString = require('crypto-random-string');
 
cryptoRandomString({length: 10});                          // => '2cf05d94db'
cryptoRandomString({length: 10, type: 'base64'});          // => 'YMiMbaQl6I'
cryptoRandomString({length: 10, type: 'url-safe'});        // => 'YN-tqc8pOw'
cryptoRandomString({length: 10, type: 'numeric'});         // => '8314659141'
cryptoRandomString({length: 6, type: 'distinguishable'});  // => 'CDEHKM'
cryptoRandomString({length: 10, type: 'ascii-printable'}); // => '`#Rt8$IK>B'
cryptoRandomString({length: 10, type: 'alphanumeric'});    // => 'DMuKL8YtE7'
cryptoRandomString({length: 10, characters: 'abc'});       // => 'abaaccabac'

cryptoRandomString.async(options)如果你想获得一个承诺,添加.async。