🔐 Web 常用加密算法分类

1. 散列(Hash)算法

单向加密,无法解密,常用于 校验、签名、存储密码

  • MD5

    • 长度固定 128 位,输出 32 位十六进制字符串。

    • 已被破解(碰撞攻击),不推荐存储密码,常用于 文件校验

    // 使用 crypto-js
    import md5 from "crypto-js/md5";
    console.log(md5("hello").toString());
    

  • SHA 系列

    • SHA-1:已不安全(被谷歌破解)。

    • SHA-256:目前主流,安全性高,输出 256 位。

    • SHA-512:更高安全性,输出 512 位。

    import sha256 from "crypto-js/sha256";
    console.log(sha256("hello").toString());
    

  • HMAC(Hash-based Message Authentication Code)

    • 在散列算法基础上加入密钥,防止篡改。

    import hmacSHA256 from "crypto-js/hmac-sha256";
    console.log(hmacSHA256("hello", "secret").toString());
    


2. 对称加密算法

加密和解密使用 同一密钥。速度快,适合 大数据加密

  • AES(Advanced Encryption Standard)

    • 常用 AES-128/192/256

    • 浏览器里常用 crypto-js 或 Web Crypto API。

    import CryptoJS from "crypto-js";
    
    const key = CryptoJS.enc.Utf8.parse("1234567890123456"); // 16位密钥
    const iv  = CryptoJS.enc.Utf8.parse("1234567890123456");
    
    const encrypted = CryptoJS.AES.encrypt("Hello AES", key, { iv }).toString();
    console.log("加密:", encrypted);
    
    const decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv }).toString(CryptoJS.enc.Utf8);
    console.log("解密:", decrypted);
    

  • DES / 3DES

    • 早期广泛使用,但安全性已不足,现在很少用。

  • ChaCha20

    • 谷歌推荐的流加密算法,用于 TLS1.3,速度快,适合移动端。


3. 非对称加密算法

加密和解密使用 不同密钥(公钥 + 私钥)。常用于 密钥交换、数字签名

  • RSA

    • 广泛用于 HTTPS。

    • 公钥加密,私钥解密;私钥签名,公钥验证。

      // 使用 jsencrypt
      import JSEncrypt from "jsencrypt";
      
      const encryptor = new JSEncrypt();
      encryptor.setPublicKey("-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----");
      
      const encrypted = encryptor.encrypt("Hello RSA");
      console.log("RSA加密:", encrypted);
      

  • ECC(椭圆曲线加密)

    • 相比 RSA,密钥更短但安全性更高。

    • 广泛用于移动端、区块链。


4. 混合加密

在实际场景里,常常 结合使用

  • 前端 → 随机生成一个对称密钥(AES)加密数据。

  • 再用 RSA 公钥加密 AES 密钥,传给后端。

  • 后端用私钥解密出 AES 密钥,再解密数据。
    👉 HTTPS 就是类似原理(TLS 握手)。


5. 前端常用的内置 API

现代浏览器提供了 Web Crypto API,比 crypto-js 更安全(底层调用原生加密库,性能好)。

示例:SHA-256

async function hashSHA256(msg) {
  const encoder = new TextEncoder();
  const data = encoder.encode(msg);
  const hash = await crypto.subtle.digest("SHA-256", data);
  return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, "0")).join("");
}

hashSHA256("hello").then(console.log);

示例:AES-GCM

async function encryptAES(message, key) {
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const enc = new TextEncoder().encode(message);
  const cryptoKey = await crypto.subtle.importKey("raw", key, { name: "AES-GCM" }, false, ["encrypt"]);
  const cipher = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, cryptoKey, enc);
  return { cipher, iv };
}


🔑 总结

类别算法适用场景
散列MD5、SHA-256校验、存储密码(加盐)
对称AES、ChaCha20数据加密(速度快)
非对称RSA、ECC密钥交换、数字签名
混合RSA + AESHTTPS、接口传输加密
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐