In this question Erik needs to generate a secure random token in Node.js.(在这个问题中, Erik需要在Node.js中生成一个安全的随机令牌。)
There's the methodcrypto.randomBytes
that generates a random Buffer.(有一个生成随机缓冲区的方法crypto.randomBytes
。) However, the base64 encoding in node is not url-safe, it includes /
and +
instead of -
and _
.(但是,节点中的base64编码不是url-safe,它包含/
和+
而不是-
和_
。) Therefore, the easiest way to generate such token I've found is(因此,生成此类令牌的最简单方法是我发现的)
require('crypto').randomBytes(48, function(ex, buf) {
token = buf.toString('base64').replace(///g,'_').replace(/+/g,'-');
});
Is there a more elegant way?(有更优雅的方式吗?)
ask by Hubert OG translate from so