CloudBranch
CloudBranch

Reputation: 1604

How can I generate a cryptographically secure pseudo-random number in Javascript?

Is there a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) in Javascript?

I know I can generate a pseudo-random number using

Math.random();

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

In Python I would use secrets() instead of random().

import secrets alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(8))

In Go I would use the crypto.rand package instead of the math/rand package.

package main

import (
    "bytes"
    "crypto/rand"
    "fmt"
)

func main() {
    c := 10
    b := make([]byte, c)
    _, err := rand.Read(b)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(bytes.Equal(b, make([]byte, c)))

}

Is there an equivalent in javascript?

Upvotes: 5

Views: 8696

Answers (1)

Nick
Nick

Reputation: 16606

In the browser, you can look into window.crypto.getRandomValues. See details here.

const array = new Uint32Array(10);
window.crypto.getRandomValues(array);

In node, take a peek at the crypto module.

const crypto = require('crypto');
crypto.randomBytes(20, (err, buffer) => {
  const token = buffer.toString('hex');
  console.log(token);
});

If you have browser support concerns, consider looking into an npm package like this one. Note: I've never used this one so I can't vouch for it.

Upvotes: 9

Related Questions