简体   繁体   English

从crypto.randomBytes中排除某些字符的正确方法

[英]correct way to exclude certain characters from crypto.randomBytes

i have the following code, based on http://nodejs.org/docs/v0.6.9/api/crypto.html#randomBytes 我有以下代码,基于http://nodejs.org/docs/v0.6.9/api/crypto.html#randomBytes

crypto.randomBytes 32, (ex, buf) ->
  user.tokenString = buf.toString("hex")
  user.tokenExpires = Date.now() + TOKEN_TIME
  next()

i am using this to generate a tokenString to use for a node.js/express user validation. 我正在使用它生成一个tokenString用于node.js / express用户验证。

in some cases the tokenString generated includes '/' forward slash character, and this breaks my routes, for example, tokenString if the tokenString is like ' $2a$10$OYJn2r/Ts.guyWqx7iJTwO8cij80m.uIQV9nJgTt18nqu8lT8OqPe ' it can't find /user/activate/$2a$10$OYJn2r and i get an 404 error 在某些情况下,生成的tokenString包含'/'正斜杠字符,这会破坏我的路由,例如,如果tokenString类似' $2a$10$OYJn2r/Ts.guyWqx7iJTwO8cij80m.uIQV9nJgTt18nqu8lT8OqPe '则无法找到/user/activate/$2a$10$OYJn2r ,我收到404错误

is there a more direct way to exclude certain characters from being included when generating the crypto.randomBytes? 是否有更直接的方法可以在生成crypto.randomBytes时排除某些字符?

Crypto.randomBytes generates random bytes . Crypto.randomBytes生成随机字节 That has nothing to do with characters, characters are determined by the way we look at the bytes. 这与字符无关,字符由我们查看字节的方式决定。

For example: 例如:

user.tokenString = buf.toString("hex")

Would convert the buffer to a string (where two characters represent each byte), in the character range 0-9a-f 将缓冲区转换为字符串(其中两个字符代表每个字节),字符范围为0-9a-f

Another (might be more suiting approach is to use a more compact encoding. Base64Url is an encoding that provides string encoding that is URL/Filename safe 另一种(可能更合适的方法是使用更紧凑的编码.Base64Url是一种提供URL /文件名安全的字符串编码的编码

user.tokenString = base64url(buf)

Here is an NPM package you can use for it . 这是您可以使用的NPM包

Other than that, your code seems fine. 除此之外,你的代码似乎很好。 If you were to call .toString() without specifying "hex" or specifying something like "ascii" for example, it would break just like in your question description. 如果您要调用.toString()而不指定"hex"或指定类似"ascii"类的东西,它就会像你的问题描述中那样破坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM