{T}

高安全架构 学习笔记(第 4 部分)

3.3 数据加密

3.3.1 加密技术对比

加密类型特点优点缺点典型算法
对称加密加解密使用同一密钥速度快、效率高密钥管理困难AES、DES、3DES
非对称加密公钥加密、私钥解密密钥管理方便速度慢、计算量大RSA、ECC
哈希算法单向加密、不可逆固定长度、唯一性无法解密MD5、SHA-256

3.3.2 对称加密实现

javascript
// AES 对称加密
const crypto = require('crypto')
 
class SymmetricEncryption {
  constructor(algorithm = 'aes-256-cbc') {
    this.algorithm = algorithm
    this.key = crypto.randomBytes(32)  // 256位密钥
    this.iv = crypto.randomBytes(16)   // 初始化向量
  }
  
  // 加密
  encrypt(plainText) {
    const cipher = crypto.createCipheriv(
      this.algorithm,
      this.key,
      this.iv
    )
    
    let encrypted = cipher.update(plainText, 'utf8', 'hex')
    encrypted += cipher.final('hex')
    
    return {
      encrypted,
      iv: this.iv.toString('hex'),
      key: this.key.toString('hex')
    }
  }
  
  // 解密
  decrypt(encryptedData, key, iv) {
    const decipher = crypto.createDecipheriv(
      this.algorithm,
      Buffer.from(key, 'hex'),
      Buffer.from(iv, 'hex')
    )
    
    let decrypted = decipher.update(encryptedData, 'hex', 'utf8')
    decrypted += decipher.final('utf8')
    
    return decrypted
  }
}
 
// 使用示例
const aes = new SymmetricEncryption()
 
const sensitiveData = '用户的敏感信息:身份证号、银行卡号等'
const encrypted = aes.encrypt(sensitiveData)
 
console.log('加密后:', encrypted.encrypted)
 
const decrypted = aes.decrypt(
  encrypted.encrypted,
  encrypted.key,
  encrypted.iv
)
 
console.log('解密后:', decrypted)

3.3.3 非对称加密实现

javascript
// RSA 非对称加密
const crypto = require('crypto')
 
class AsymmetricEncryption {
  constructor() {
    // 生成密钥对
    const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
      modulusLength: 2048,
      publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
      },
      privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem'
      }
    })
    
    this.publicKey = publicKey
    this.privateKey = privateKey
  }
  
  // 公钥加密
  encryptWithPublicKey(plainText) {
    const buffer = Buffer.from(plainText, 'utf8')
    
    const encrypted = crypto.publicEncrypt(
      {
        key: this.publicKey,
        padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
        oaepHash: 'sha256'
      },
      buffer
    )
    
    return encrypted.toString('base64')
  }
  
  // 私钥解密
  decryptWithPrivateKey(encryptedData) {
    const buffer = Buffer.from(encryptedData, 'base64')
    
    const decrypted = crypto.privateDecrypt(
      {
        key: this.privateKey,
        padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
        oaepHash: 'sha256'
      },
      buffer
    )
    
    return decrypted.toString('utf8')
  }
  
  // 数字签名
  sign(data) {
    const sign = crypto.createSign('SHA256')
    sign.update(data)
    sign.end()
    
    const signature = sign.sign(this.privateKey, 'base64')
    
    return signature
  }
  
  // 验证签名
  verify(data, signature) {
    const verify = crypto.createVerify('SHA256')
    verify.update(data)
    verify.end()
    
    return verify.verify(this.publicKey, signature, 'base64')
  }
}
 
// 使用示例
const rsa = new AsymmetricEncryption()
 
// 加密解密
const plainText = '敏感数据'
const encrypted = rsa.encryptWithPublicKey(plainText)
const decrypted = rsa.decryptWithPrivateKey(encrypted)
 
console.log('加密后:', encrypted)
console.log('解密后:', decrypted)
 
// 数字签名
const data = '需要签名的数据'
const signature = rsa.sign(data)
const isValid = rsa.verify(data, signature)
 
console.log('签名:', signature)
console.log('验证结果:', isValid)  // true

3.3.4 HTTPS 实现

HTTPS 工作原理

plaintext
HTTPS 加密流程:
 
客户端                                    服务器
  │                                         │
  │  1. 请求建立 HTTPS 连接                 │
  │ ──────────────────────────────────────→ │
  │                                         │
  │  2. 返回 SSL 证书(包含公钥)            │
  │ ←────────────────────────────────────── │
  │                                         │
  │  3. 验证证书有效性                       │
  │  4. 生成随机会话密钥                     │
  │  5. 用公钥加密会话密钥                   │
  │ ──────────────────────────────────────→ │
  │                                         │
  │  6. 用私钥解密会话密钥                   │
  │                                         │
  │  7. 使用会话密钥加密通信                 │
  │ ←─────────────────────────────────────→ │
  │                                         │