TypeScript 中的密码学:加密与哈希实践

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

TypeScript 中的密码学:加密与哈希 — 完全指南



现代 Web 开发离不开数据安全保障。TypeScript 作为 JavaScript 的超集,在客户端和服务器端(Node.js)都提供了强大的密码学功能实现工具。本文将详细讲解基本密码学原语:对称与非对称加密、哈希,以及数字签名的使用。所有代码示例均使用 TypeScript 编写,可直接用于实际项目。



1. TypeScript 密码学基础



在 TypeScript 生态中,主要有两种密码学实现方式:

  • Web Crypto API — 浏览器和 Node.js(自版本 15 起)内置的 API,提供对密码学操作的底层访问。
  • 第三方库 — 例如 crypto-js、node-forge、bcryptjs,用于特定任务。


对于 Node.js 服务器端开发,建议使用内置的 crypto 模块,它是平台的一部分,无需安装额外依赖。



2. 数据哈希



哈希是将数据转换为固定长度的单向变换。它用于密码存储、文件完整性校验和生成校验和。



2.1. 使用 Web Crypto API 进行 SHA-256 哈希



async function hashSHA256(data: string): Promise<string> {  const encoder = new TextEncoder();  const dataBuffer = encoder.encode(data);  const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);  const hashArray = Array.from(new Uint8Array(hashBuffer));  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');}

// 使用示例const myHash = await hashSHA256('你好,世界!');console.log(myHash); // 64 个十六进制字符


2.2. 使用 bcrypt 进行密码哈希



为了安全存储密码,请使用带盐的专用算法,例如 bcrypt:



import bcrypt from 'bcryptjs';

async function hashPassword(password: string): Promise<string> { const salt = await bcrypt.genSalt(12); // 12 轮 — 良好的平衡 return await bcrypt.hash(password, salt);}

async function verifyPassword(password: string, hash: string): Promise<boolean> { return await bcrypt.compare(password, hash);}

// 示例const password = 'MySecurePass!';const hashedPassword = await hashPassword(password);const isValid = await verifyPassword('MySecurePass!', hashedPassword);console.log(isValid); // true


3. 对称加密



对称加密使用同一个密钥进行数据的加密和解密。最现代且安全的算法是 AES-GCM,它同时提供机密性和认证。



3.1. AES-GCM 加密与解密



interface EncryptedData {  iv: Uint8Array;  ciphertext: Uint8Array;  tag: Uint8Array;}

async function encryptAESGCM( plaintext: string, key: CryptoKey): Promise<EncryptedData> { const encoder = new TextEncoder(); const data = encoder.encode(plaintext); const iv = crypto.getRandomValues(new Uint8Array(12)); // 96 位 IV const encrypted = await crypto.subtle.encrypt( { name: 'AES-GCM', iv }, key, data ); // GCM 在末尾添加 16 字节的认证标签 const ciphertext = new Uint8Array(encrypted.slice(0, encrypted.byteLength - 16)); const tag = new Uint8Array(encrypted.slice(encrypted.byteLength - 16)); return { iv, ciphertext, tag };}

async function decryptAESGCM( encrypted: EncryptedData, key: CryptoKey): Promise<string> { // 合并 ciphertext 和 tag 以供 Web Cry

推荐