How to generate random bytes in Node.JS

Easy! I discovered this recently and it is interesting to me. Here is a quick example: const crypto = require(‘crypto’); console.log(crypto.randomBytes(1).toString(“hex”)); console.log(crypto.randomBytes(2).toString(“hex”)); console.log(crypto.randomBytes(4).toString(“hex”)); console.log(crypto.randomBytes(8).toString(“hex”)); console.log(crypto.randomBytes(16).toString(“hex”)); console.log(crypto.randomBytes(32).toString(“hex”)); console.log(crypto.randomBytes(64).toString(“hex”)); When you run this code you might see something similar to this: E:\NodeJS>node randomCrypto.js d8 dccd 0709fee2 67d6d7c51cc59f0d af19069e601e47a9141d27d7d828a9d0 f83b7547452099462061734791da57443cc60828de7dcb8f7494eedceb3c889c e2e4a1faaf4190898aaf4fa786e20fe076237854ae4628127cb2eda4bafd3000b42788e347ade94d0c98614a40586b71ded3044879f791adedd6c0d4bb22e9ac The argument passed to the function is the length in bytes, when …

Elliptic Curve Diffie-Hellman and AES Example in Node.JS

Recently I learned how to generate shared secrets using ECDH in Node.JS, but I still had to know how to use this shared secret. Here is one application for it. Use the ECDH to generate a shared secret and then use that shared secret to cipher/decipher messages between both parties, in this case Joe and Zoe. Here is the code: …

How to generate Diffie Hellman key pair in Node.JS

Super easy using crypto library. You can create a file called DiffieHellmanKeyPairGeneration.js for example and paste this code inside: console.log(‘\n- — ( Diffie Hellman Key Pair Generator ) — -‘); var crypto = require(‘crypto’); var bitSize = 2048; var dh = crypto.createDiffieHellman(bitSize); dh.generateKeys(); console.log(‘Private Key:\n’ + dh.getPrivateKey(‘base64’)); console.log(‘\n’); console.log(‘Public Key:\n’ + dh.getPublicKey(‘base64’)); console.log(‘— End —‘); Then run it, wait…wait…wait…wait…wait…wait…, and you …

How to generate SHA256HMAC in Node.JS

Today I had to do this for my job (hash some info) and I think is a good opportunity to share the knowledge. Here is the code, you can simply copy it and paste it in a file called SHA256Hmac.js and run it. let crypto; try {     crypto = require(‘crypto’); } catch (err) {     console.log(‘crypto support is disabled!’); …