加密方式

在现代应用开发中,密码加密是保障用户数据安全的关键环节。以下是常见的密码加密方式及其应用场景,附带示例代码:

1. 哈希加密(单向加密)

将密码转换为固定长度的哈希值,无法逆向解密。常用算法:BCrypt、Argon2、PBKDF2、Scrypt。

推荐方案:BCrypt(安全且广泛使用)

javascript
// Node.js + bcrypt 示例
const bcrypt = require('bcrypt');

async function hashPassword(password) {
  const saltRounds = 10;
  return await bcrypt.hash(password, saltRounds);
}

async function verifyPassword(password, hashedPassword) {
  return await bcrypt.compare(password, hashedPassword);
}

// 使用示例
const password = "MySecurePassword123";
hashPassword(password).then(hashed => {
  console.log("哈希值:", hashed); // $2b$10$...
  verifyPassword(password, hashed).then(isValid => {
    console.log("密码验证:", isValid); // true
  });
});

2. 对称加密(双向加密)

使用相同密钥加密和解密。常用算法:AES、DES。
应用场景:需要还原明文的场景(如加密配置文件)。

示例:AES-256-CBC

javascript
// Node.js + crypto 示例
const crypto = require('crypto');

function encrypt(text, secretKey) {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-cbc', secretKey, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return iv.toString('hex') + ':' + encrypted;
}

function decrypt(encryptedText, secretKey) {
  const [ivHex, encryptedHex] = encryptedText.split(':');
  const iv = Buffer.from(ivHex, 'hex');
  const decipher = crypto.createDecipheriv('aes-256-cbc', secretKey, iv);
  let decrypted = decipher.update(encryptedHex, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

// 使用示例
const secretKey = crypto.randomBytes(32); // 256-bit 密钥
const encrypted = encrypt("敏感数据", secretKey);
console.log("加密后:", encrypted);
console.log("解密后:", decrypt(encrypted, secretKey));

3. 非对称加密(公钥加密)

使用公钥加密,私钥解密。常用算法:RSA、ECC。
应用场景:安全传输密钥、数字签名。

示例:RSA 加密
javascript
 
// Node.js + crypto 示例
const crypto = require('crypto');

// 生成密钥对
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

// 加密
function encryptWithPublicKey(text) {
  const encrypted = crypto.publicEncrypt(
    { key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING },
    Buffer.from(text)
  );
  return encrypted.toString('base64');
}

// 解密
function decryptWithPrivateKey(encryptedText) {
  const decrypted = crypto.privateDecrypt(
    { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING },
    Buffer.from(encryptedText, 'base64')
  );
  return decrypted.toString('utf8');
}

// 使用示例
const encrypted = encryptWithPublicKey("机密信息");
console.log("加密后:", encrypted);
console.log("解密后:", decryptWithPrivateKey(encrypted));

4. 密码哈希 + 加盐(最佳实践)

为防止彩虹表攻击,需对密码附加随机盐值再哈希。

示例:PBKDF2 哈希 + 加盐

javascript
 
// Node.js 示例
const crypto = require('crypto');

function hashPassword(password) {
  const salt = crypto.randomBytes(16).toString('hex');
  const hash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
  return `${salt}:${hash}`;
}

function verifyPassword(password, storedHash) {
  const [salt, hash] = storedHash.split(':');
  const generatedHash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
  return hash === generatedHash;
}

// 使用示例
const hashed = hashPassword("SecurePassword");
console.log("加盐哈希:", hashed); // salt:hash
console.log("验证结果:", verifyPassword("SecurePassword", hashed)); // true

5. 现代密码哈希算法对比

算法安全性性能适用场景
BCrypt 中等 通用(默认推荐)
Argon2 极高 中等 对安全性要求极高的场景
Scrypt 移动设备
PBKDF2 兼容性要求高的场景

安全建议

  1. 永远不要明文存储密码,必须使用哈希 + 加盐。
  2. 定期更新加密算法,如从 MD5/SHA-1 迁移到 BCrypt/Argon2。
  3. 使用密钥扩展函数(如 PBKDF2)增加破解难度。
  4. 设置合理的计算成本(如 BCrypt 的 saltRounds),平衡安全性和性能。
  5. 避免自定义加密算法,使用成熟的库(如 Node.js 的 crypto、Python 的 bcrypt)。

根据应用场景选择合适的加密方式,优先考虑 BCrypt 或 Argon2 作为密码哈希方案。
posted @ 2025-05-23 13:13  张筱菓  阅读(123)  评论(0)    收藏  举报