javascriptjavanode.jscryptographysecure-random

Java SecureRandom Instance SHA1PRNG equivalent in Node.JS/


I need to translate a function in Java to Node JS

    public byte[] GetId() throws NoSuchAlgorithmException {
      byte[] byArray = new byte[4];
      byte[] byArray2 = new byte[8];
      SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
      secureRandom.nextBytes(byArray);
      secureRandom.nextBytes(byArray2);
      return byArray2;
    }

So what's the equivalence of secureRandom.getInstance and nextBytes to Javascript?

Do I need to use crypto library? like:

crypto.randomBytes(8)

?


Solution

  • The function you're looking for is indeed crypto.randomBytes. That's the appropriate way to generate cryptographically secure random numbers in Node.JS.

    Also note that in Java, you don't really want to explicitly use the SHA1PRNG implementation if you can avoid it. It's much better to use the OS default PRNG if possible, since the SHA1PRNG has some known weaknesses, so you'd just write new SecureRandom(), which will do the right thing on every platform.