Node.js crypto Module

Java FileNode.js Built-in Modules


Node.js'scryptoThe module is a built-in module that provides cryptographic functionality, including wrappers for OpenSSL's hash, HMAC, encryption, decryption, signing, and verification functions. It allows developers to perform various cryptographic operations in Node.js applications.


Core Functions

Hash Algorithm

A hash algorithm is a one-way function that converts input of any length into a fixed-length output.cryptoThe module supports multiple hash algorithms, such as SHA-256, MD5, etc.

Example

const crypto = require('crypto');

// Create a SHA-256 hash
const hash = crypto.createHash('sha256');
hash.update('Hello World');
console.log(hash.digest('hex'));
// Output: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146

HMAC (Keyed-Hash Message Authentication Code)

HMAC is a message authentication mechanism that uses a cryptographic hash function combined with a secret key.

Example

const crypto = require('crypto');

const secret = 'mysecret';
const hmac = crypto.createHmac('sha256', secret);
hmac.update('Hello World');
console.log(hmac.digest('hex'));
// Output: 9b8e8b0e3b9e9b1a3b9e9b1a3b9e9b1a3b9e9b1a3b9e9b1a3b9e9b1a3b9e9b1a

Encryption and Decryption

Symmetric Encryption

Symmetric encryption uses the same key for both encryption and decryption.cryptoThe module supports algorithms such as AES and DES.

Example

const crypto = require('crypto');

// Encrypt
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('Hello World', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);

// Decrypt
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);

Asymmetric Encryption

Asymmetric encryption uses a public/private key pair; the public key is used for encryption, and the private key is used for decryption.

Example

const crypto = require('crypto');

// Generate key pair
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

// Encrypt
const encryptedData = crypto.publicEncrypt(
  publicKey,
  Buffer.from('Hello World')
);
console.log(encryptedData.toString('base64'));

// Decrypt
const decryptedData = crypto.privateDecrypt(
  privateKey,
  encryptedData
);
console.log(decryptedData.toString());

Digital Signature and Verification

Digital signatures are used to verify the integrity and origin of data.

Example

const crypto = require('crypto');

// Generate key pair
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

// Create signature
const sign = crypto.createSign('SHA256');
sign.update('some data to sign');
const signature = sign.sign(privateKey, 'hex');
console.log(signature);

// Verify signature
const verify = crypto.createVerify('SHA256');
verify.update('some data to sign');
console.log(verify.verify(publicKey, signature, 'hex'));
// Output: true

Random Number Generation

cryptoThe module provides methods for generating cryptographically secure random numbers.

Example

const crypto = require('crypto');

// Generate 16 bytes of random data
const randomBytes = crypto.randomBytes(16);
console.log(randomBytes.toString('hex'));

// Generate a random integer
const randomInt = crypto.randomInt(1, 100);
console.log(randomInt);

Security Considerations

  1. Key management: Never hardcode keys in code; use environment variables or a key management system.
  2. Algorithm selection: Avoid using known insecure algorithms such as MD5 and SHA1.
  3. **Initialization Vector (IV)**: For symmetric encryption, a different IV should be used for each encryption.
  4. Cryptographic parameters: Use sufficiently long key lengths (e.g., AES-256 instead of AES-128).

Practical Application Scenarios

  1. Password storage: Use hash algorithms to store user passwords
  2. Data transmission encryption: Protect data in network transmission
  3. API signature verification: Ensure the integrity of API requests
  4. JWT tokens: Generate and verify JSON Web Tokens
  5. File integrity checking: Verify the hash of downloaded files

Summary

Node.js'scryptoThe module provides powerful cryptographic functions and is an important tool for building secure applications. By properly using hash, encryption, signing, and other features, developers can effectively protect data security. When using it, be sure to follow security best practices and choose appropriate algorithms and parameters.

For more complex security needs, consider using dedicated cryptographic libraries such asbcrypt、argon2etc., which are optimized for specific purposes.

Java FileNode.js Built-in Modules

Other Extensions