1

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 faking someone else's url and also base64 encode to minimize the length of the url created.

http://myurl.com/~hashedtoken where un-hashed hashtoken could be something like this 55q322q23 55 = userid

I thought about using crypto library like so:

crypto.createHash('md5').update("55q322q23").digest("base64");

which returns: u/mxNJQaSs2HYJ5wirEZOQ== The problem here is that I have the / which is not considered websafe so I would like to strip the un-safe letters from the base64 list of letters, somehow. Any ideas about this or perhaps a better solution to the problem at hand?

2 Answers 2

2

You could use a so called URL safe variant of Base64. The most common variant, described in RFC 4648, uses - and _ instead of + and / respectively, and omits padding characters (=).

Most implementations of Base64 support this URL safe variant too, though if yours doesn't, it's easy enough to do manually.

1
  • I end up using urlsafe-base6 npm library for what you describe. I encode to base64(unsafe) then use library to encode to safe. Commented Jul 14, 2013 at 19:47
0

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 @).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.