a blog for those who code

Monday 10 November 2014

Cryptography in Nodejs

In this post we will see how to implement cryptography in Nodejs and various types of hashing algorithms available in Nodejs.

According to Gary C. Kessler, The Purpose of Cryptography is
Cryptography, then, not only protects data from theft or alteration, but can also be used for user authentication. There are, in general, three types of cryptographic schemes typically used to accomplish these goals: secret key (or symmetric) cryptography, public-key (or asymmetric) cryptography, and hash functions, each of which is described below. In all cases, the initial unencrypted data is referred to as plaintext. It is encrypted into ciphertext, which will in turn (usually) be decrypted into usable plaintext.
Thus security is a critical part of any application regardless of the framework you choose.

At first we will see what are the hash algorithms available in Nodejs. When you run the below code you will get all the hash algorithms available in Nodejs.

var crypto = require('crypto');
console.log(crypto.getHashes().join('; '));

Output :

Now we know that what are the available hashes in nodejs, thus we will secure a message using one of the hash. Before going into the code we will look into the createHash() and createHmac() function of the crypto module.

According to Nodejs Documentation

cypto.createHash(algorithm) : It creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digest.

crypto.createHmac(algorithm, key) : It creates and returns a hmac object with the given algorithm and key.

Code :

var crypto = require('crypto');


crypto.getHashes().forEach(function(hash) {

var hashedMessage = crypto.createHash(hash).update('Hello World').digest('hex');
        var hmacedMessage = crypto.createHash(hash, 'secret key').update('Hello World').digest('hex');
console.log(hash, hashedMessage);
        console.log(hash, hmacedMessage);


crypto.getHashes().forEach(function(hash) {

var hashedMessage = crypto.createHash(hash).update('Hello World').digest('base64');
        var hashedMessage = crypto.createHash(hash, 'secret key').update('Hello World').digest('base64');
console.log(hash, hashedMessage);
        console.log(hash, hmacedMessage);

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment