Loading lesson path
Concept visual
Start from A
Formula
The Crypto module is a built - in Node.js module that provides cryptographic functionality including:
Hash functions (SHA - 256, SHA - 512, etc.)
HMAC (Hash - based Message Authentication Code)Symmetric encryption (AES, DES, etc.) Asymmetric encryption (RSA, ECDSA, etc.)
The Crypto module is essential for applications that need to handle sensitive information securely.
Formula
The Crypto module wraps the OpenSSL library, providing access to well - established and tested cryptographic algorithms.This module is often used to handle sensitive data, such as:
Here's a quick example of using the Crypto module to hash a string:
const crypto = require('crypto');
// Create a SHA-256 hash of a string const hash = crypto.createHash('sha256').update('Hello, Node.js!').digest('hex');
console.log('SHA-256 Hash:', hash);The Crypto module is included in Node.js by default. You can use it by requiring it in your script:
const crypto = require('crypto');Formula
Hashing is a one - way transformation of data into a fixed - length string of characters.Hash functions have several important properties:
Output is always the same size regardless of input size
Small changes in input produce significant changes in output
Content addressing (e.g., Git, IPFS)
Creating a Hash const crypto = require('crypto');
// Create a hash object const hash = crypto.createHash('sha256');
// Update the hash with data hash.update('Hello, World!');
// Get the digest in hexadecimal format const digest = hash.digest('hex');
console.log(digest);createHash() creates a hash object with the specified algorithm update() updates the hash content with the given data digest() calculates the digest and outputs it in the specified format
Common Hash Algorithms const crypto = require('crypto');
const data = 'Hello, World!';Formula
// MD5 (not recommended for security - critical applications)const md5 = crypto.createHash('md5').update(data).digest('hex');
console.log('MD5:', md5);Formula
// SHA - 1 (not recommended for security - critical applications)const sha1 = crypto.createHash('sha1').update(data).digest('hex');
console.log('SHA-1:', sha1);
// SHA-256 const sha256 = crypto.createHash('sha256').update(data).digest('hex');
console.log('SHA-256:', sha256);
// SHA-512 const sha512 = crypto.createHash('sha512').update(data).digest('hex');
console.log('SHA-512:', sha512);Formula
MD5 and SHA - 1 are considered cryptographically weak and should not be used for security - critical applications.
Use SHA - 256, SHA - 384, or SHA - 512 instead.When handling passwords, it's crucial to use specialized password hashing functions that are designed to be computationally expensive to prevent brute-force attacks. Here's why simple hashes are insufficient:
Formula
Never store passwords in plain text or with simple hashes like MD5 or SHA - 1.
These can be easily cracked using rainbow tables or brute - force attacks.