Skip to content

Instantly share code, notes, and snippets.

@AmrSaber
Last active April 11, 2020 19:36
Show Gist options
  • Save AmrSaber/578c4c1b9d9c1f0a6ce5dd23bf9c3b4c to your computer and use it in GitHub Desktop.
Save AmrSaber/578c4c1b9d9c1f0a6ce5dd23bf9c3b4c to your computer and use it in GitHub Desktop.
JS Secure Random Float
const crypto = require('crypto')
function getSecureFloat() {
// Generate 7 random bytes
const bytes = crypto.randomBytes(7);
// Shift 5 bits from first bytes by 5 to the right
let randomValue = (bytes[0] % (2 ** 5)) / (2 ** 5);
// For each of the following 6 bytes, add its value and shift it 8 bits to the right
bytes.slice(1).forEach(byte => { randomValue = (randomValue + byte) / (2 ** 8); });
// randomValue now has a floating point number that is 53 bits long
return randomValue;
}
@AmrSaber
Copy link
Author

AmrSaber commented Apr 9, 2020

This is an implementation for what is proposed in this answer for generating a random floating-point number that is cryptographically secure in javascript.

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