Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In this question Erik needs to generate a secure random token in Node.js.(在这个问题中, Erik需要在Node.js中生成一个安全的随机令牌。)

There's the method crypto.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
293 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try crypto.randomBytes() :(尝试crypto.randomBytes() :)

require('crypto').randomBytes(48, function(err, buffer) { var token = buffer.toString('hex'); }); The 'hex' encoding works in node v0.6.x or newer.('hex'编码在节点v0.6.x或更新版本中有效。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...