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

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
Higher Order Functions in JavaScript with ExamplesJavaScriptJavaScript: Methods for HTML DOM classList PropertyJavaScriptCreate a simple bar chart and column chart using pure CSS gridCSSSelector Lists and Combinators in SCSS (Sass)SCSSCreate dynamic selectors using SCSS (Sass)SCSSArbitrary Arguments in SCSS functionsSCSSComposing and Extracting Components in ReactReactHow to create rotating texts using JavaScript and CSS?CSSWhat is Prototypal Inheritance in JavaScript?JavaScriptHow to reference an aliased column in the WHERE clause?SQL/MySQLList of social media icon logo color codes in HEXMiscellaneousHow to compress images with gulp in WordPress?WordPress