How to perform encryption and decryption of messages using Crypto in Node.js?

Reading Time: 9 minutes
How to perform encryption and decryption of messages using Crypto in Node.js?

Web applications have access to massive amounts of data belonging to individuals, organizations, and governments. The more data that is accessed, the greater the risk to data security. Cryptography and encryption techniques are used by software developers to protect sensitive data from malicious parties.

Cryptography is used to protect data stored in a database or transferred over a network in the software development industry. You must handle, move, and store data in a safe and secure manner.

As a result, as a Node.js developer, you must understand how to encrypt and decrypt data in order to secure the data processed by your system. For data encryption and decryption, Node.js includes a built-in library called crypto.

The goal of encryption and decryption is to increase security. This blog will show you how to use Crypto in Node.js to encrypt and decrypt messages with step-by-step instructions. Let’s get started! 🚀

Cryptography in Node.js

For software development, cryptography is essential. The process of converting plain text into unreadable text and vice versa is known as cryptography. Only the sender and receiver of the information understand its content in this manner.

Cryptography in Node.js

You can hash passwords in Node.js and store them in the database so that data cannot be converted to plain text after it has been hashed; it can only be verified. When malicious actors gain access to your database, they will be unable to decode the encrypted data. Other user data can also be encrypted and decrypted during transmission.

What exactly is a Node.js crypto module?

The Node.js crypto module provides cryptographic functions to aid in the security of your Node.js application. It includes wrappers for the hash, HMAC, cypher, decipher, sign, and verify functions of OpenSSL.

Because crypto is built into Node.js, it does not necessitate a lengthy implementation process or configurations. Unlike other modules, Crypto does not require installation before being used in a Node.js application.

Crypto Classes in Node.js

Let’s take a look at the crypto classes that allow us to implement cryptography.

  • Cipher: The Cipher class is in charge of encrypting data. The Cipher class is invoked when a user enters a password during registration to encrypt the password.
  • Decipher: Decrypting encrypted texts is the responsibility of the Decipher class. When sending information securely to another developer, you must encrypt it. The only way for the recipient to read the information is to decrypt it. This is precisely what the Decipher class accomplishes.
  • Hash: The Hash class is used for hashing plain text. Hashing is simply the conversion of plain text into hash functions.
  • Certificate: A Certificate consists of a key pair and other information used to encrypt electronic documents. A certificate can generate a session key for the purpose of securely transmitting data over the internet. With the crypto Certificate class, you can use OpenSSL’s SPKAC implementation to work with Signed Public Key and Challenge (SPKAC).
Crypto Classes in Node.js
  • DiffieHellman: Diffie-Hellman key exchanges are used by Crypto’s DiffieHellman class. Diffie-Hellman key exchange is a technique for securely transmitting cryptographic keys over public networks. This protects keys that are only used by information senders and receivers.
  • ECDH: Elliptic-curve The Diffie-Hellman (ECDH) algorithm is used to create a shared public-private key pair with an elliptic curve.
  • HMAC: With the use of a shared secret, hash-based message authentication code (HMAC) allows you to provide digital signatures. The HMAC method is used by Crypto’s HMAC class for digital signing.
  • sign: The sign class is used to generate signatures. Cryptographs must be signed and later verified for authentication in order for cryptography to be efficient. When the receiver receives a cryptograph, they can check the signature to see if it is genuine.
  • verify: The only way to determine the value of a hashed cryptography is to use the verify method.

Hands-on

Required installations for the process?

  • Node.js: It is a JavaScript runtime environment that executes JavaScript code outside the browsers.
  • Crypto: It is an inbuilt Node.js package that provides cryptographic operations to help secure Node.js applications.

In this hands-on, we will have a look at how we can make use of the crypto package in node.js to encrypt and decrypt a secret message. To do so, we will first begin with creating the package.json file and then initialize npm within the newly created directory. Then we will install the crypto package for using it for encryption and decryption. Verifying the package installation, we will then proceed further and import the package into our codebase. We will then define the type of algorithm that we will be used for encryption and the decryption purpose.

Then we will make use of the package to generate 16 bytes and 32 bytes of random data to be able to use it as a secret key for the encryption purpose. Defining the input and the output type, we will test out the encrypted output. On success, we will use the same package to perform the decryption process. Once done, we will then test out the decrypted message as well and verify the same with the message that we encrypted.

Note: Please ensure that Node.js is properly installed onto the local machine or else it might display multiple errors while following the process.

Create a new directory on your local machine.

IMG_256

Open the newly created directory into a code editor.

IMG_257

Right-click in the left navigation pane and click on New file.

Create a new file with the name package.json.

Right-click in the newly created directory and click on Git Bash Here.

encryption and decryption of messages using Crypto in Node.js

Run the command: npm init

Enter a name for the pkg and press enter to continue with the default settings.

encryption and decryption of messages using Crypto in Node.js

Finally, you will see the structure as shown in the image below.

You can cross-verify the same by looking at the package.json file.

encryption and decryption of messages using Crypto in Node.js

Now, we need to install the crypto package. To do the same:

Execute the command: npm install crypto --save

On successful installation, you will see the result as shown in the image below.

If you look at the file structure, you will get to see the following structure.

Open the package.json file to verify the installation of the crypto package.

encryption and decryption of messages using Crypto in Node.js

Now, in the file structure, create a new file with the name index.js.

Open the index.js file and import the crypto package using the code as shown in the image below.

Now, to perform the encryption process, we need to use an algorithm. Use the code as shown in the image below. We will be using the ‘aes-256-cbc’ algorithm.

The crypto.randomBytes() inbuilt method of the crypto package is used to generate random data of 16 bytes or 32 bytes as provided in its argument. The inVec (ie. The initialization vector) is used to store the 16 bytes of random data from the crypto.randomBytes() inbuilt method.

Initialize a variable consisting of the secret message.

encryption and decryption of messages using Crypto in Node.js

The secKey (ie. Securitykey) stored the 32 bytes of random data generated using crypto.randomBytes() inbuilt method.

We need to use the inbuilt cipher function (ie. createCipheriv()) for encrypting the data. It takes three arguments as follows:

  • The type of algorithm to be used for encryption
  • The security key (variable holding 32 bytes of randomly generated data)
  • The initialization vector (variable holding 16 bytes of randomly generated data)
encryption and decryption of messages using Crypto in Node.js

Finally, in order to encrypt the message, we need to use the update() inbuilt method of the crypto package which takes the argument as follows:

  • The message to be encrypted
  • The input encoding style (utf-8)
  • The output encoding style (hex)

Now, when encryption is being performed, we need a way to stop the execution of the algorithm once the message is encrypted. To do so, we can use the final() inbuilt method using the code as shown in the image below and finally console out the encrypted message.

encryption and decryption of messages using Crypto in Node.js

Run the application using the command:

node index.js

On successful execution, you will see the encrypted message as the output as shown in the image below.

Now, since the encryption is done, we need to perform the decryption of the message as well. To do so, we will make use of the createDecipheriv() inbuilt function of the crypto package. It takes the following as the arguments:

  • The type of algorithm to be used for decryption
  • The security key (variable holding 32 bytes of randomly generated data)
  • The initialization vector (variable holding 16 bytes of randomly generated data)

To decipher the message, we will make use of the update() inbuilt method that takes in the following arguments:

  • The encrypted message
  • The input encoding style (hex)
  • The output encoding style (utf-8)

Finally, once the decryption is performed, we will have to stop the execution of the algorithm. To do so, we will again make use of the final() inbuilt method using the code as shown in the image below and output the decrypted message.

The entire code along with the encryption and decryption of the message is shown in the image below.

encryption and decryption of messages using Crypto in Node.js

Run the application using the command:

node index.js

On successful execution, you will see the encrypted and the decrypted message as shown in the image below.

Conclusion

In this hands-on, we had a look at how we can make use of the crypto package in Node.js to encrypt and decrypt a secret message.

To do so, we first began with creating the package.json file and then initialized npm within the newly created directory. Then we installed the crypto package for using it for encryption and decryption.

Verifying the package installation, we then proceeded further and imported the package into our codebase. We then defined the type of algorithm that we would use for encryption and the decryption purpose.

Then we made use of the package to generate 16 bytes and 32 bytes of random data to be able to use it as a secret key for the encryption purpose. Defining the input and the output type, we tested out the encrypted output.

On success, we used the same package to perform the decryption process. Once done, we then tested out the decrypted message as well and verified the same with the message that we encrypted. We will come up with more such use cases in our upcoming blogs.

Meanwhile…

If you are an aspiring Node Lover and want to explore more about the above topics, here are a few of our blogs for your reference:

Keep Exploring -> Keep Learning -> Keep Mastering 

At Workfall, we strive to provide the best tech and pay opportunities to kickass coders around the world. If you’re looking to work with global clients, build cutting-edge products and make big bucks doing so, give it a shot at workfall.com/partner today!

Back To Top