Published on

How to Generate a Random Hash in JavaScript

Authors

If you need to generate a random hash-like string in JavaScript, you can use the crypto module in Node js. For example, to generate a SHA1-like random hash:

const crypto = require('crypto');

// this will mimic a SHA-1 hash (20 bytes)
const n = 20;
const hash = crypto.randomBytes(n).toString('hex');
console.log(hash);

// or as a one-liner
require('crypto').randomBytes(20).toString('hex');

Or if you want to use something other than a SHA1-like hash, you can use the crypto module more comprehensively like:

const crypto = require('crypto');

const n = 20;
const salt = crypto.randomBytes(n);
const hash = crypto.createHash('sha256').update(salt).digest('hex');
console.log(hash);

Since the goal is just a random hash-like string, this is quick and easy. Thanks to crypto.randomBytes, we don’t have to worry so much about collisions.

Or, if you need just a one-off string, you can just use this already compiled random hash generator.

Either way, you can read more about the crypto module in the Node documentation. As for which algorithms are available for crypto.createHash(), you can use openssl list -digest-algorithms on your environment to find which algorithms are available.