阿里云主机折上折
  • 微信号
Current Site:Index > Encryption and hashing

Encryption and hashing

Author:Chuan Chen 阅读数:7710人阅读 分类: Node.js

In Node.js development, encryption and hashing are core technologies for ensuring data security. Although often confused, they serve different purposes: encryption is reversible and used to protect sensitive information during transmission, while hashing is irreversible and commonly employed for password storage and data integrity verification.

Fundamentals of Encryption

Node.js provides encryption capabilities through the crypto module, supporting symmetric encryption (e.g., AES) and asymmetric encryption (e.g., RSA). Symmetric encryption uses the same key for both encryption and decryption, making it suitable for large data volumes. Asymmetric encryption uses public/private key pairs, offering higher security but lower performance.

AES Encryption Example:

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

function encrypt(text) {
  let cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

console.log(encrypt('secret data')); // Output encrypted result

Applications of Hash Functions

Hash functions map data of arbitrary length to fixed-length values and are one-way. In Node.js, commonly used algorithms include SHA-256 and MD5 (not recommended), primarily for password storage and file verification.

Salted Password Hashing Example:

const crypto = require('crypto');

function hashPassword(password, salt) {
  return crypto.pbkdf2Sync(
    password,
    salt,
    100000,
    64,
    'sha512'
  ).toString('hex');
}

const salt = crypto.randomBytes(32).toString('hex');
console.log(hashPassword('user123', salt)); // Store hash and salt

Key Derivation Functions

PBKDF2, scrypt, and similar algorithms are specifically designed to derive keys from passwords, increasing computational complexity to prevent brute-force attacks. Node.js's crypto.scrypt implements memory-intensive computations, making it more resistant to ASIC attacks.

scrypt Example:

crypto.scrypt('password', 'salt', 64, { N: 16384 }, (err, derivedKey) => {
  console.log(derivedKey.toString('hex'));
});

Message Authentication Codes

HMAC combines hashing with a secret key to verify message integrity and authenticity. It is commonly used in API signature verification scenarios.

HMAC-SHA256 Implementation:

const hmac = crypto.createHmac('sha256', 'secret-key');
hmac.update('data to verify');
console.log(hmac.digest('hex'));

Performance and Security Trade-offs

Encryption operations consume CPU resources. In web servers, consider the following:

  • Synchronous APIs block the event loop.
  • Adjust PBKDF2 iteration counts to balance security and performance.
  • Use crypto.createCipheriv instead of the deprecated createCipher.

Asynchronous Encryption Example:

crypto.pbkdf2('password', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));
});

Practical Use Cases

  1. HTTPS Communication: TLS protocols combine symmetric and asymmetric encryption.
  2. JWT Tokens: HMAC or RSA signatures verify token validity.
  3. Database Encryption: Field-level encryption protects user privacy data.
  4. Blockchain: Hash chains ensure data immutability.

JWT Signature Verification Snippet:

const jwt = require('jsonwebtoken');
const token = jwt.sign({ user: 'admin' }, 'hmac-secret', { algorithm: 'HS256' });
jwt.verify(token, 'hmac-secret', (err, decoded) => {
  console.log(decoded); // { user: 'admin' }
});

Common Vulnerability Mitigations

  1. Weak Hash Algorithms: Avoid MD5/SHA-1; prefer SHA-256/512.
  2. Salt Reuse: Use unique random salts for each password.
  3. ECB Mode: Use CBC or GCM modes for AES instead.
  4. Key Management: Avoid hardcoding keys; use environment variables or key management systems.

Secure Random Number Generation:

// Insecure
Math.random().toString(36).substring(2);

// Secure method
crypto.randomBytes(32).toString('hex');

Node.js Version Differences

Encryption support varies across Node.js versions:

  • Starting with v10.0.0, the default iteration count for pbkdf2 increased from 1,000 to 100,000.
  • v15.0.0 deprecated createCipher/createDecipher.
  • v17.0.0 added limited implementation of the Web Crypto API.

Version-Compatible Code:

const { createCipheriv, createDecipheriv } = crypto;
// Replaces deprecated createCipher

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:会话管理

下一篇:CSRF防护

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.