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

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

还有更优雅的方式吗?


当前回答

npm模块anyid提供了灵活的API来生成各种字符串ID /代码。

使用48个随机字节在A-Za-z0-9中生成随机字符串:

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

生成由随机字节填充的固定长度的字母字符串:

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

在内部,它使用crypt . randombytes()来生成random。

其他回答

查看:

var crypto = require('crypto');
crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);

在你的终端上写

node -e "console.log(crypto.randomBytes(48).toString('hex'))"

尝试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');

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

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