Websafe encoding of hashed string in nodejs

前端 未结 2 1842
失恋的感觉
失恋的感觉 2021-01-25 05:34

I am creating a re-director of sorts in nodejs. I have a few values like userid // superid

these I would like to hash to prevent users from retrieving the url and fakin

2条回答
  •  醉梦人生
    2021-01-25 05:41

    Here's what I used. Comments welcome :-)

    The important bit is buffer.toString('base64'), then URL-safeing that base64 string with a couple of replace()s.

    function newId() {
      // Get random string with 20 bytes secure randomness
      var crypto = require('crypto');
      var id = crypto.randomBytes(20).toString('base64');
      // Make URL safe
      return id.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }
    

    Based on the implementation here.

    Makes a string safe for URL's and local email addresses (before the @).

提交回复
热议问题