Skip to content

Instantly share code, notes, and snippets.

@nuria
Last active August 23, 2018 21:38
Show Gist options
  • Select an option

  • Save nuria/29cc52fa908b1b551c3919852ac63576 to your computer and use it in GitHub Desktop.

Select an option

Save nuria/29cc52fa908b1b551c3919852ac63576 to your computer and use it in GitHub Desktop.
Performance tests. RandomGenerator with 80 bits of entropy.
<html>
<head>
</head>
<body>
<script>
function generateRandomWith5_16Bits() {
var rnds, i,
hexRnds = new Array( 5 ),
// Support: IE 11
crypto = window.crypto || window.msCrypto;
// Fill an array with 5 random values, each of which is 16 bits.
// Note that Uint16Array is array-like but does not implement Array.
rnds = new Uint16Array( 5 );
crypto.getRandomValues( rnds );
// Convert the 5 16bit-numbers into 20 characters (2 hex per 8 bits)
for ( i = 0; i < 5; i++ ) {
// Add 0x1000 before converting to hex and strip the extra character
// after converting to keep the leading zeros.
hexRnds[ i ] = ( rnds[ i ] + 0x10000 ).toString( 16 ).slice( 1 );
}
// Concatenation of two random integers with entropy n and m
// returns a string with entropy n+m if those strings are independent
return hexRnds.join( '' );
}
function generateRandomWith1_16Bits_232Bits() {
var rnds,_16BitRnd, i,
hexRnds = new Array( 3 ),
// Support: IE 11
crypto = window.crypto || window.msCrypto;
// Fill an array with 5 random values, each of which is 16 bits.
// Note that Uint16Array is array-like but does not implement Array.
rnds = new Uint32Array( 2 );
crypto.getRandomValues( rnds );
_16BitRnd = new Uint16Array(1);
crypto.getRandomValues(_16BitRnd);
// Convert the 2 32bit-numbers into 16 characters (2 hex per 8 bits)
for ( i = 0; i < 2; i++ ) {
// Add 0x1000 before converting to hex and strip the extra character
// after converting to keep the leading zeros.
hexRnds[ i ] = ( rnds[ i ] + 0x100000000 ).toString( 16 ).slice( 1 );
}
hexRnds[2] = ( _16BitRnd[ 0 ] + 0x10000 ).toString( 16 ).slice( 1 );
// Concatenation of two random integers with entropy n and m
// returns a string with entropy n+m if those strings are independent
return hexRnds.join( '' );
}
// calling both
var start = performance.now();
var r1 = generateRandomWith5_16Bits();
var end = performance.now()-start;
console.log(start-end);
start = performance.now();
var r2 = generateRandomWith1_16Bits_232Bits();
var end = performance.now()-start;
console.log(start-end);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment