Crypto

The Node.js Crypto module supports cryptography. It provides cryptographic functionality that includes a set of wrappers for open SSL's hash HMAC, cipher, decipher, sign and verify functions.

What is Hash

A hash is a fixed-length string of bits i.e. procedurally and deterministically generated from some arbitrary block of source data.

What is HMAC

HMAC stands for Hash-based Message Authentication Code. It is a process for applying a hash algorithm to both data and a secret key that results in a single final hash.

Encryption Example using Hash and HMAC

File: crypto_example1.js

snippet
const crypto = require('crypto');
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
                   .update('Welcome to rookienerd')
                   .digest('hex');
console.log(hash);

Open Node.js command prompt and run the following code:

snippet
node crypto_example1.js
Node.js crypto example 1

Encryption example using Cipher

File: crypto_example2.js

snippet
const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
var encrypted = cipher.update('Hello rookienerd', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);

Open Node.js command prompt and run the following code:

snippet
node crypto_example2.js
Node.js crypto example 2

Decryption example using Decipher

File: crypto_example3.js

snippet
const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
var encrypted = '4ce3b761d58398aed30d5af898a0656a3174d9c7d7502e781e83cf6b9fb836d5';
var decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);

Open Node.js command prompt and run the following code:

snippet
node crypto_example3.js
Node.js crypto example 3
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +