How to quickly generate random secure token with nodejs and etc.

with crypto package programmatically

const crypto = require('crypto');

const secretKey = 'secret key';
const data = 'Hello World';

const hmac = crypto.createHmac('sha256', secretKey);
hmac.update(data);

console.log(hmac.digest('hex'));

with crypto package from the command line

node -p "crypto.randomBytes(16).toString('hex')"
node -p "crypto.randomBytes(16).toString('base64')"

with Buffer from the command line

$ node -p "Buffer.from('hello').toString('base64')"
aGVsbG8=
$ node -p "Buffer.from('aGVsbG8=', 'base64').toString()"
hello
$ node -p "Buffer.from('hello').toString('hex')"
68656c6c6f
$ node -p "Buffer.from('68656c6c6f', 'hex').toString()"
hello

with openssl command line tool

openssl rand -hex 32
openssl rand -base64 32
Post tagged with: nodejs, ssl