Hashing numbers using the hashids module in Node.js

The following example shows how you can encrypt and decrypt numbers using the hashids module in Node.js.

First, create a new directory, add a new JavaScript file, app.js, and copy/paste the following code:

#!/usr/bin/env node 

// Native modules
var assert = require("assert");

// 3rd party modules
var hashids = require("hashids");

// Create our hash object with the specified 'salt'.
var hash = new hashids("correct horse battery staple");

var arr = [1976, 7, 19];

// Encrypt a set of numbers by passing multiple arguments.
var enc = hash.encrypt(1976, 7, 19);
var dec = hash.decrypt(enc);

// Make sure we get the expected hash for the supplied arguments.
assert.equal(enc, 'dbeGfMUg');
assert.deepEqual(dec, arr);

// Make sure the first decrypted value was the first passed argument.
assert.equal(dec[0], 1976);

// Encrypt a set of numbers using `Function.apply()` and passing an array.
var enc2 = hash.encrypt.apply(hash, arr);
var dec2 = hash.decrypt(enc2);

// Make sure we get the expected hash for the supplied arguments.
// Note: These values should be the same as `enc` and `dec` above,
// despite being called via `Function.apply()`.
assert.equal(enc2, 'dbeGfMUg');
assert.deepEqual(dec2, arr);

// Assert that the encrypted and decrypted values are the same,
// regardless of how they were invoked.
assert.equal(enc, enc2);
assert.deepEqual(dec, dec2);

console.log("Everything passes!");

Next, install the hashids module by typing the following command in your Terminal (in the same directory as the app.js file created above):

$ npm install hashids

Finally, run the code by typing the following command in to the Terminal:

$ node app.js

In the code above we’re creating a new hash object instance by calling the hashids constructor and passing in a unique salt value.

Next, we encrypt a series of numbers by passing multiple arguments to the encrypt() method to create a hashed string. By calling the decrypt() method, we can convert the numbers encrypted earlier back in to an array of numbers (the same numbers we passed as arguments to our encrypt method).

The example also shows how you can use JavaScript’s Function.apply() method to pass the numeric values to be encrypted as an array rather than as separate arguments.

Leave a Reply

Your email address will not be published.