Common things I do in node.
Generate a Secure Random String
16-byte (128-bit) random url-safe base64-encoded string:
let crypto = require('crypto');
crypto
.randomBytes(16)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
function rnd(len, enc) {
let crypto = require('crypto');
return crypto
.randomBytes(len || 16)
.toString(enc || 'base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
Hash some Bytes
let str = "Hello, 🌎!"; // or hex, base64, etc
let buf = Buffer.from(str, 'utf-8');
crypto.createHash('sha256').update(buf).digest('base64');