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.
crypto ModuleThe 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!
Let's start with a simple example: creating a hash with SHA256.
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.
Next, let's learn how to encrypt and decrypt data using the crypto module.
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!
HMAC (Hash-based Message Authentication Code) is used to verify the integrity of a message. Let's create an HMAC for a message.
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.
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! š