YogeshChauhan . com

How to create a secure random number using JavaScript?

in JavaScript on October 13, 2020

To create a secure random number, we will use getRandomValues() method from window.crypto

Step 1: Get a random number using getRandomValues()


var cryptoRandom = window.crypto.getRandomValues(new Uint32Array(1))[0];

console.log(cryptoRandom);

// 2557767905

Step 2: Divide that number with a similar large number.

To do we need to use JavaScript pow() Method. It returns the value of x to the power of y.

After division, we will get the random number in a fraction of a zero.


var cryptoRandom2 = cryptoRandom / (Math.pow(2, 32) - 1);

console.log(cryptoRandom2);

// 0.8196058019110015

Step 3: Multiply with 10 to remove the fraction.


cryptoRandom3 = cryptoRandom2 * 10;

console.log(cryptoRandom3);

// 8.175500582013163

Step 4: Use Math.floor to get single digit random number.


console.log(Math.floor(cryptoRandom3));

// 8

NOTE: If you run the code chunks separately then you will get a different number each time. 

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to create ‘share on LinkedIn’ link using just HTML?HTMLHow to get Current Year, Month and Date in JavaScript?JavaScriptHow to add a ribbon inside a container using CSS?CSSthe box-sizing property in CSSCSSMicroservices vs Monolithic ArchitectureMiscLearn to make a responsive gallery using CSS Grid and without media queriesCSSFULL OUTER JOIN in PostgresPostgresHow to display and animate image on scroll using JavaScript?JavaScriptSQL ANY OperatorSQL/MySQLRecursive WITH Queries in Postgres (Common Table Expressions)PostgresIs there a way to do a FULL OUTER JOIN in MySQL?SQL/MySQLHow to create a sticky menu pin using CSS?CSS