Last active
April 11, 2020 19:36
-
-
Save AmrSaber/578c4c1b9d9c1f0a6ce5dd23bf9c3b4c to your computer and use it in GitHub Desktop.
JS Secure Random Float
This file contains hidden or 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 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an implementation for what is proposed in this answer for generating a random floating-point number that is cryptographically secure in javascript.