šŸŽÆ Node.js Crypto Module Tutorial

beginner
8 min

šŸŽÆ Node.js Crypto Module Tutorial

Welcome to our deep dive into the crypto module in Node.js! This tutorial is designed for both beginners and intermediates, so let's get started.

šŸ“ Understanding the crypto Module

The crypto module is a built-in Node.js library that provides various cryptographic functions. These functions can be used for encryption, decryption, creating digital signatures, and more!

šŸŽÆ Creating a Hash with SHA256

Let's start with a simple example: creating a hash with SHA256.

javascript
const crypto = require('crypto'); const text = 'Hello World!'; const hash = crypto.createHash('sha256'); hash.update(text); const hashedText = hash.digest('hex'); console.log(hashedText); // Outputs: 'a94a8fe5ccb19b5e59f2891b78db62d37e4eb64a3b14d6963b63b42b43b68e51'

šŸ’” Pro Tip: Hashes are unique strings generated from data and are useful for checking the integrity of data.

šŸŽÆ Encrypting and Decrypting Data

Next, let's learn how to encrypt and decrypt data using the crypto module.

javascript
const crypto = require('crypto'); const cipher = crypto.createCipher('aes192', 'secretKey'); const plainText = 'Top Secret Message'; const encryptedText = cipher.update(plainText, 'utf8', 'hex') + cipher.final('hex'); console.log(encryptedText); // Outputs: 'b37844c3c3608747a87b3bdaa384156b' const decipher = crypto.createDecipher('aes192', 'secretKey'); const decryptedText = decipher.update(encryptedText, 'hex', 'utf8') + decipher.final('utf8'); console.log(decryptedText); // Outputs: 'Top Secret Message'

šŸ’” Pro Tip: Always use a secure key for encryption and never share it with others!

šŸŽÆ Working with HMAC

HMAC (Hash-based Message Authentication Code) is used to verify the integrity of a message. Let's create an HMAC for a message.

javascript
const crypto = require('crypto'); const message = 'An important message'; const secret = 'a secret key'; const hmac = crypto.createHmac('sha256', secret); hmac.update(message); const hmacMessage = hmac.digest('hex'); console.log(hmacMessage); // Outputs: '793f0a4d8d4b2c12e82a600810e99e3a584a8e67585489543753d1f44b732b47'

šŸ’” Pro Tip: HMACs can help prevent data tampering during transmission.

šŸŽÆ Quiz Time!

Quick Quiz
Question 1 of 1

What is the primary purpose of the `crypto` module in Node.js?

That's all for today! In the next lesson, we'll explore more advanced features of the crypto module. Keep coding! šŸŽ‰