Skip to content

Instantly share code, notes, and snippets.

@vip3r011
Created February 4, 2023 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vip3r011/217a08e142e85d19f887cb864a83f0b9 to your computer and use it in GitHub Desktop.
Save vip3r011/217a08e142e85d19f887cb864a83f0b9 to your computer and use it in GitHub Desktop.
secure random in nodejs
'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