关于javascript:在Node.js中保护随机令牌

Secure random token in Node.js

在这个问题中,erik需要在node.js中生成一个安全的随机令牌。有一种方法可以生成随机缓冲区。但是,节点中的base64编码不是URL安全的,它包括/+,而不是-_。因此,生成这种令牌的最简单方法是

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

有更优雅的方式吗?


(P)Try Crypto.Randombytes():(p)字母名称(P)The'hex'encoming works in node V0.6.x or newer.(p)


(P)如果你不是一个像我这样的JS专家的话关于如何获得内线函数变量的问题,需要花点时间(p)字母名称


0.利用纳米第三部分图书馆注布尔奇1(P)https://github.com/ai/nanoid(p)字母名称(P)(p)1.基地64 Encding with URL and filename safe alphabet(P)Page 7 of RCF 4648 describes how to encide in base 64 with URL safety.You can use a existing library like base64URL to do the job.(p)(P)The function will be:(p)字母名称(P)Usage example:(p)字母名称(P)Note that the returned string length will not match with the size argument(size!页:1(p)(P)(p)2.Crypto random values from limited set of characters布尔奇1(P)You can also build a strong random string from a limited set of characters like that:(p)字母名称(P)Usage example:(p)字母名称


(P)The up-to-date right way to do this asynchronously using ES 2016 standards of ASYNC and await(as of node 7)would be the following:(p)字母名称(P)This works out of the box in node 7 without any babel transformations(p)


(P)Random URL and filename string safe(1 lines)(p)字母名称


(P)With ASYNC/Await and Promise.(p)字母名称(P)类似的几代人(p)


(P)Look at EDOCX1 English 0 Es2016 way,it's more correct.是的。(p)Ecmascript 2016(ES7)way字母名称(P)(p)创造者/Yield Way字母名称


(P)检查出来:(p)字母名称


(P)NPM module anyid provides flexible API to generate various kinds of string id/code.(p)(P)To generatite random string in a-za-Z0-9 using 48 random bytes:(p)字母名称(P)To generate fixed length alphabet only string filled by random bytes:(p)字母名称(P)Internally it used EDOCX1 theocx1 generation random.(p)


(P)https://www.npmjs.com/package/crypto-extra has a method for it:(p)字母名称


(P)Here is an async version taken verbatim from above@yves m.'s answer(p)字母名称