Skip to content

Instantly share code, notes, and snippets.

@muthu32
Created March 3, 2025 13:30
Show Gist options
  • Save muthu32/d6034cba2d710dd03b76faa36911bf31 to your computer and use it in GitHub Desktop.
Save muthu32/d6034cba2d710dd03b76faa36911bf31 to your computer and use it in GitHub Desktop.
Insecure Random Fortify Math.random alternative
function generateRandom() {
// Generate a secure random 32-bit unsigned integer
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
// Convert the random integer to a floating-point number between 0 (inclusive) and 1 (exclusive)
return randomBuffer[0] / (0xFFFFFFFF + 1);
}
@harimnarayana32
Copy link

for nodejs use below code

const crypto = require("crypto");

function generateRandom() {
  // Generate a secure random 32-bit unsigned integer
  const randomBuffer = new Uint32Array(1);
  crypto.webcrypto.getRandomValues(randomBuffer);

  // Convert the random integer to a floating-point number between 0 (inclusive) and 1 (exclusive)
  return randomBuffer[0] / (0xFFFFFFFF + 1);
}

console.log(generateRandom()); // Example usage

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