Skip to content

Instantly share code, notes, and snippets.

@faazshift
Created July 30, 2018 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faazshift/0f9d9722bcfc036f4a2925f8d2444d61 to your computer and use it in GitHub Desktop.
Save faazshift/0f9d9722bcfc036f4a2925f8d2444d61 to your computer and use it in GitHub Desktop.
Small, portable and suitably unique random ID functions for typical web application use
function uniqueId() {
var a = new Uint8Array(12);
crypto.getRandomValues(a);
return btoa([].slice.call(a).map(function(c) {
return String.fromCharCode(c);
}).join('')).replace(/[/+=]/g, '');
}
const crypto = require('crypto');
function uniqueId() {
return crypto.randomBytes(12).toString('base64').replace(/[/+=]/g, '');
}
<?php
function uniqueId()
{
$bytes = function_exists('random_bytes') ? random_bytes(12) : openssl_random_pseudo_bytes(12);
return preg_replace('~[/+=]~', '', base64_encode($bytes));
}

Each of the functions in this Gist use a system provided source of cryptographically secure random bytes. Typical, built-in random number functions are weak and unreliable for true randomness. These functions are small, dependency-free and fairly portable across different language versions and environments. They have each been tested repeatedly over many millions of iterations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment