Yogesh Chauhan's Blog

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. 


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
What are components in Angular?AngularObservation of Human Behavior [Shopping Observation Example]Miscellaneous@forward modules with a prefix in SCSS (Sass)SCSSPHP Login System using PDO Part 2: Login using Email or UsernamePHPPre-defined DatePipe format options in Angular 9AngularHow to use GROUPING SETS to boost GROUP BY queries in Postgres?PostgresWordPress get_posts ExamplesWordPressDebugging in WordPress Part 3: SCRIPT_DEBUG and SAVEQUERIESWordPressDifference between :where and :is in CSSCSSThe SELECT DISTINCT Statement in SQLSQL/MySQLHow to show widgets on the Appearance tab in WordPress?WordPressA Step by Step Guide to Make RSS in XML For Any Website or Blog For FreeMiscellaneous