Created
February 4, 2023 19:54
-
-
Save vip3r011/217a08e142e85d19f887cb864a83f0b9 to your computer and use it in GitHub Desktop.
secure random in nodejs
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
'use strict'; | |
const crypto = require('crypto'); | |
class RNG { | |
// Define a static method for generating a random float value in the range of 0 to 1 | |
static random() { | |
try { | |
// Use the crypto module's randomBytes method to generate 4 random bytes | |
const randomBytes = crypto.randomBytes(4); | |
// Interpret the random bytes as a 32-bit unsigned integer using readUInt32LE | |
const int = randomBytes.readUInt32LE(0); | |
// Divide the integer by 0xffffffff to get a float value in the range of 0 to 1 | |
const float = int / 0xffffffff; | |
// Return the generated float value | |
return float; | |
} catch (err) { | |
// Re-throw the error if it occurs | |
throw err; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment