Generate securely random string in Nodejs

Asked

Viewed 990 times

3

How, using the Javascript language on the Nodejs platform, generate a string, preferably with configurable size, random enough to be used in routines dealing with cryptography and that for safety reasons cannot be insufficiently random?

If you propose more than one solution, preferably clarify which one you think is more random, possibly with external additional references. Solutions involving more than one source of randomness generator are also welcome, in particular if accompanied by explanation of advantages, such as reducing problems with an operating system explicitly changed by an NSA of life to generate less chaos when producing randomness.

Even if two people propose the same code, if one of these explains better or proves with real examples the dispersion of values, it will be considered as the best answer. It is not enough to copy and paste code, you should discuss why it is a good solution.

Solutions that directly access an operating system resource, using for example exec = require('child_process').exec; //(...) are also welcome.

Note: Please do not propose solutions that require access to an external network service. The solution should use only the language and operating system where it is running. Accessing any service via HTTP outside of an internal network not only impacts performance but is also a cause of security failure.

1 answer

3

Use the module Crypto:

var crypto = require('crypto');
crypto.randomBytes(tamanho, function (erro, resultado /*buffer*/) {
  if (erro) {throw erro;}
  console.log('Uma string aleatória de %d bytes: %s', resultado .length, resultado);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.