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.
Created
July 30, 2018 20:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, ''); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('crypto'); | |
function uniqueId() { | |
return crypto.randomBytes(12).toString('base64').replace(/[/+=]/g, ''); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function uniqueId() | |
{ | |
$bytes = function_exists('random_bytes') ? random_bytes(12) : openssl_random_pseudo_bytes(12); | |
return preg_replace('~[/+=]~', '', base64_encode($bytes)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment