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)
?
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
SHA1PRNGimplementation if you can avoid it. It's much better to use the OS default PRNG if possible, since theSHA1PRNGhas some known weaknesses, so you'd just writenew SecureRandom(), which will do the right thing on every platform.