Cryptography in Node.JS

Learn via video courses

Overview

Web apps have access to vast volumes of data, posing additional threats to data security. Cryptography and encryption techniques are used by software developers to secure sensitive data from hostile parties. As a result, as a node.js developer, you must know how to decrypt and encrypt data to safeguard the information processed by your system. For data encryption and decryption, Node.js includes a built-in library named crypto which we will discuss in detail.

Introduction

For software development, cryptography is essential. Data must be safeguarded. A study of data security methods is known as cryptography. It turns plaintext into encrypted text and vice versa, transforming the information into a secret. As a result, only the receiver and the sender of that data can comprehend its contents.

A cryptosystem is made up of three basic parts: plaintext, ciphertext, and algorithm. We employ a cypher and an algorithm that converts plaintext into ciphertext to conceal information. Data is encrypted when it is made into unintelligible text, and it is returned to plaintext when data is decrypted.

A key is used by cryptographic algorithms to change plaintext into ciphertext. If you have the correct key on hand, it is feasible to convert the ciphertext back to plaintext.

Encryption

If you use the same key to encrypt and decode data, you are utilizing symmetric encryption. If different keys are utilized for encryption and decryption, asymmetric encryption is employed. You must keep hashed passwords in the database to secure data in Node.js apps. In this manner, material that has been hashed cannot be decoded into plaintext. It needs to be confirmed. The data is encrypted, so even if malevolent attackers get to access the database, they won't be able to read it. Furthermore, they lack the key that would enable them to do so.

Both encryption and decoding work to increase security. Data that is exchanged across a network or kept in a database is secured using cryptography. This tutorial will teach you how to encrypt and decode data in your applications using the Node.js crypto module. It will also provide a node.js cryptography summary.

Mechanism in Cryptography

Hashing :-

A succession of ordinary text is essentially transformed into Ciphertext in this process. Since we are unable to change this encrypted text back to the plain text again, this cryptographic algorithm is one-way.

This technique is mostly utilized when supplying sensitive passwords to systems for user authentication. These ciphertexts will be kept on file since passwords cannot be. Message Digest 5 (MD5), RSA, SHA, and other widely used hashing algorithms are a few examples of prominent hashing algorithms.

Encryption and Decryption:-

A secret key is used in this process to encrypt a string of plain text, which is subsequently decrypted using the same key. Without a secret key, it is impossible to decrypt the text and restore the original text.

This algorithm accepts as inputs encrypted text and a secret key, and it outputs the original text. Most messaging systems employ this approach to guard against data leaks of any kind on the network. AES, DES, etc., are a few common techniques.

Node.js Crypto Module

To help you secure your Node.js application, the Node.js crypto module offers cryptographic operations. In addition to cyphers and deciphers, it provides hashes and HMAC for authentication.

Node.js Crypto Module

Crypto is a built-in library in Node.js, as was already mentioned. As a result, it doesn't need to be downloaded or set up before being used in Node.js apps. The data encryption and decryption algorithm are handled by the crypto module.

Before putting information into a database, you can hash plain texts with the help of the crypto module. Like encrypted data, hashed data cannot be decoded using a specific key. Instead, a Hash-based Message Authentication Code (HMAC) is in charge of hashing keys and data to produce a final hash.

For transmission, you might want to encrypt and decrypt data. Here are the cypher and decipher functions. You use a cypher function to encrypt data and a decipher function to decode it. Before putting data in the database, you can also want to encrypt it.

To validate passwords that have been encrypted or hashed. It is preferable to have a verify function. Let us just look at the decryption and encryption of data and how to use crypto to build Node.js applications.

Features of Crypto Module

  • Easy to use- The crypto module has a very easy-to-follow pattern of use.
  • Widely used algorithms- There are a large number of algorithms that can be used for both hashing and cyphers with multiple options. They are dependent on the OpenSSL of the system.
  • Cleaner and Consistent Code- The crypto module’s utilities can be easily embedded in the business logic of the code without building any inconsistency in the code.
  • Easy Integration- The crypto module is a built-in module in Node.js and its functions can be easily used in the logic of the application.

Usage of Crypto Module

Numerous types of OpenSSL cryptographic functions are wrapped under the crypto module. It can perform hash computations, HMAC authentication, cyphers, and much more!

The crypto module's primary function is to implement cryptographic protocols like TLS and https. The built-in tls and https modules should satisfy the majority of users. However, those who want to deal with full-scale cryptography can utilize the crypto module.

Hashing

A hash is a fixed-length string of bits generated from any arbitrary block of source data using some technique and specified stages.

The hash has several properties :

  • Fixed length: This means that the hash length remains constant regardless of the input. For instance, regardless of whether the input data is a few bits or a few gigabytes, SHA-256 hashes are always 256 bits long.
  • Deterministic: For the same input, you should anticipate receiving the same hash. Hashes are useful for checksums as a result.
  • Collision Resistant: When the same hash is calculated for two different data input blocks, a collision occurs. Hash algorithms are designed to clash very rarely; their level of unlikeliness is one of their characteristics. The use case dictates the importance of this attribute.
  • Unidirectional: A good hash algorithm is straightforward to use but challenging to undo. This indicates that it is impossible to identify the original set of data given a hash string.

Hash Algorithms That Work With Crypto:

The version of OpenSSL you are using determines the hashes that work with the crypto module. Run 'openssl list -digest-algorithms' from the command line to get a list of hash types if your version of OpenSSL is recent enough. Instead, for older versions, enter openssl list-message-digest-commands

One of the most used hashing algorithms is SHA-256. Older common types, like SHA-1 and MD5, are no longer secure and should no longer be used.

How To Calculate Hashes with Crypto:

The hash string is generated using the crypto module's 'createHash' method. The name of the hash algorithm is the only parameter this function requires.

It is necessary to push data into the update method so that it may be used by the digest method to turn it into a hash. 'update' can be called numerous times to read streaming data, such as buffers from a file read stream. The output format for the digest function is specified by a parameter that can be either binary, hex, or base64. By default, it's set to binary.

Here is an example to find the hash of a string with the sha-256 algorithm.

The following output will be produced :

Let us take a look at a small example involving the use of the crypto module and a different algorithm.

The following output will be produced :

Encryption/ Decryption

Ciphers enable you to encrypt and decrypt messages using a password.

Cipher Algorithms That Work With Crypto:

The cyphers that operate with crypto, like the hash algorithms, are depending on what your version of OpenSSL provides. You may acquire a list of hash types supported by your OpenSSL by running openssl list-cipher commands. AES 256 is a solid and popular encryption supported by OpenSSL.

How To Use Cipher Algorithms with Crypto:

The crypto module has two methods - one for encrypting and one for decrypting :

  • crypto.createCipheriv(algorithm, key, iv)
  • crypto.createDecipheriv(algorithm, key, iv)

The first argument is the name of the algorithm as a string. The key is the raw key used by the algorithm, and iv is an initialization vector. key must be secret, and the iv must be unique but need not be secret.

Creates and returns a Cipher object with the given algorithm, key, and initialization vector (iv). iv is required to provide randomness. Randomization is critical for encryption systems to ensure semantic security, which is the feature that repeated use of the scheme under the same key does not allow an attacker to deduce links between encrypted message segments.

Both of the above methods have update functions. The update function returns a chunk of the encoded/decoded data. Hence the digest function is not required to get the result. To get the last chunk of encoded data, you need to call the final method.

Note : The crypto.createCipheriv() and crypto.createDecipheriv() methods do not accept a password. Instead, the key and the initialization vector are used to generate a random password. The sizes of these two arguments are fixed based on the algorithm.

Here is the table showing the sizes :

AlgorithmKeyiv
aes12816 byte (128 bits)16 byte (128 bits)
aes-128-cbc16 byte (128 bits)16 byte (128 bits)
aes19224 byte (192 bits)16 byte (128 bits)
aes25632 byte (256 bits)16 byte (128 bits)

Encryption:

Now let us try to implement the encryption of a short string with the help of a crypto module. Write the following code in a .js file and run it.

You will get an output similar to :

In the above code, the aes-256-cbc algorithm has been used to encrypt the data. The crypto module has been imported.

The crypto.randomBytes() function is used to produce cryptographically constructed random data from written code. The iv (initialization vector) holds 16 bytes of random data generated from the randomBytes() function, while the Securitykey has 32 bytes of random data.

To encrypt the data, the cipher function is made with the help of the createCipheriv function, key, and the iv. The update function is used to convert the message to an encrypted form. The input and output encoding is also specified in the update function. The final method is used to stop the encryption. After calling final, encryption cannot be done anymore.

Decryption:

The decryption also follows the same pattern. Make the changes in your encryption code as given below :

On running the above code you will get the output similar to the following :

The decipher function is created using the createDecipheriv. The algorithm of encryption, the key, and the same initialization vector is used. The update is used to convert the encrypted message with specified encoding to the decrypted text with the output encoding. The final method is used to get the final chunk of decrypted data.

Certificate

A Certificate consists of a key pair and additional information required to encrypt electronic documents.

A certificate can generate a session key to securely send data over the internet. With the crypto Certificate class, you may use OpenSSL's SPKAC implementation to interact with Signed Public Key and Challenge (SPKAC).

Below is an example of how to use the Certificate class:

DiffieHellman

The DiffieHellman class is used to implement the Diffie-Hellman key exchanges.

The crypto.getDiffieHellman() method helps in creating a predefined DiffieHellmanGroup key exchange object. Here, the several preferred groups are modp14, modp15, modp16, modp17, modp18, defined in RFC 3526, and modp1, modp2, modp5, which are defined in RFC 2412.

Syntax :

  • Parameters: The group name of the type string is the only argument.
  • Return Type: DiffieHellmanGroup key exchange object is returned.

The above code will give the following output :

HMAC

HMAC is an abbreviation for Hash-based Message Authentication Code. The hash algorithm is applied to data and a key to form a final secret hash.

The crypto.createHmac() method creates an HMAC object with the specified algorithm and key.

Syntax:

Parameters: There are three parameters

  • algorithm: It is the algorithm that is supported by the OpenSSL of the platform.
  • key: The HMAC key is used to generate the cryptographic HMAC hash. It can be a string, Buffer, TypedArray, DataView, or KeyObject.
  • Options: An optional parameter to control stream behavior.

Return Type: It returns an Hmac object.

The output of the above code will be similar to :

ECDH

The crypto.createECDH() method is a function in the crypto module used to create an Elliptic Curve Diffie-Hellman i.e, (ECDH) key exchange object with the help of a predefined curve in the form of a string. The crypto.getCurves() method can be used to get the list of available curve names.

Syntax:

Parameters: Single parameter that is the curveName, a string is accepted.

Return Value: It returns ECDH key exchange object.

The output will be similar to :

Sign

Cryptographs must be signed and later verified for authentication for cryptography to be efficient. The crypto.createSign() method is used to generate a sign object with the help of a specified algorithm. The crypto.getHashes() method can be used to get the name of algorithms.

Syntax:

Parameters: Two parameters are required.

  • algorithm: It is a string-type value that is the name of the algorithm.
  • options: It is an optional parameter that is used to control the behavior of the stream.

Return Value: It returns the Sign object.

The following sign object will be returned :

Verify

The only way to determine the value of a hashed cryptograph is to use the verify method. A verify object can be created using crypto.createVerify() method and the specified algorithm. The crypto.getHashes() method can be used to get the name of algorithms.

Syntax:

Parameters: Two parameters are required.

  • algorithm: It is a string-type value that is the name of the algorithm.
  • options: It is an optional parameter that is used to control the behavior of the stream.

Return Value: It returns the Verify object.

An output similar to the following will be received :

Conclusion

  • A cryptosystem is made up of three basic parts: plaintext, ciphertext, and algorithm.
  • If you use the same key to encrypt and decode data, you are utilizing symmetric encryption.
  • If different keys are utilized for encryption and decryption, asymmetric encryption is employed.
  • There are two mechanisms in cryptography, namely hashing and encryption/decryption.
  • To help you secure your Node.js application, the Node.js crypto module offers cryptographic operations.
  • A hash is a fixed-length string of bits generated from any arbitrary block of source data using some technique and specified stages.
  • Ciphers enable you to encrypt and decrypt messages using a password.
  • Diffie-Hellman key exchange is a technique for securely transmitting cryptographic keys across public networks.
  • HMAC is an abbreviation for Hash-based Message Authentication Code.