secure random nodejs
const crypto = require('crypto');
function generateSecureRandomString(length) {
return new Promise((resolve, reject) => {
crypto.randomBytes(length, (err, buffer) => {
if (err) {
reject(err);
} else {
const randomString = buffer.toString('hex');
resolve(randomString);
}
});
});
}
const lengthOfRandomString = 10;
generateSecureRandomString(lengthOfRandomString)
.then(randomString => {
console.log(`Secure random string of length ${lengthOfRandomString}: ${randomString}`);
})
.catch(error => {
console.error('Error generating secure random string:', error);
});
Explanation:
- crypto
is a built-in Node.js module that provides cryptographic functionality.
- crypto.randomBytes(length, callback)
generates cryptographically strong pseudo-random data of the specified length.
- generateSecureRandomString
is a function that takes the desired length as a parameter and returns a Promise.
- Inside the generateSecureRandomString
function, crypto.randomBytes
is used to generate random bytes.
- If there's an error during the generation of random bytes, the Promise is rejected with the error.
- If the random bytes are generated successfully, they are converted to a hexadecimal string using buffer.toString('hex')
.
- The Promise is resolved with the resulting random string.
- Finally, a random string of the specified length is generated by calling generateSecureRandomString
with the desired length and handling the resolved Promise to log the generated secure random string or to catch and log any errors that might occur during the process.