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 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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to Pop an Alert Box in PHP?JavaScriptWhat are partials in SCSS (Sass)?SCSSUseful (and probably ignored) HTML tags: Part 1HTMLIntroduction to Angular modules Part 1: NgModule metadataAngularJavaScript: Methods for HTML DOM classList PropertyJavaScriptHow to get ACF values from custom post type?WordPressHow to create a CSS full page background image?CSSArray.from() Method in JavaScriptJavaScriptWhen you don’t want to @forward every member in SCSS (Sass)SCSSHow to define variables in SCSS (Sass)?SCSSapply_filters function in WordPressWordPressHow to compile and watch Sass using Gulp in WordPress?SCSS