简体   繁体   中英

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

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.

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

is there a more direct way to exclude certain characters from being included when generating the crypto.randomBytes?

Crypto.randomBytes generates random bytes . 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

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

user.tokenString = base64url(buf)

Here is an NPM package you can use for it .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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