javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > 前端实现加密

前端实现加密的常见方法和步骤

作者:liangshanbo1215

这篇文章主要介绍了前端实现加密的常见方法和步骤,包括对称(AES)、非对称(RSA/ECC)及哈希(SHA-256)算法,推荐使用WebCryptoAPI、CryptoJS等工具,需要的朋友可以参考下

前言

在前端实现加密是一种常见的安全措施,用于保护敏感数据(如密码、用户信息等)在传输或存储过程中的安全性。以下是实现前端加密的常见方法和步骤:

1. 常见的加密方式

(1) 对称加密

(2) 非对称加密

(3) 哈希算法

2. 实现前端加密

(1) 使用 Web Crypto API (推荐)

Web Crypto API 是浏览器原生提供的加密接口,支持现代加密标准。

// 加密函数
async function encryptData(plainText, secretKey) {
  const encoder = new TextEncoder();
  const data = encoder.encode(plainText);
  
  // 使用AES-GCM算法
  const iv = window.crypto.getRandomValues(new Uint8Array(12));
  const encrypted = await window.crypto.subtle.encrypt(
    {
      name: "AES-GCM",
      iv: iv
    },
    secretKey,
    data
  );
  
  return {
    iv: Array.from(iv).join(','),
    ciphertext: Array.from(new Uint8Array(encrypted)).join(',')
  };
}

// 生成密钥
async function generateKey() {
  return await window.crypto.subtle.generateKey(
    {
      name: "AES-GCM",
      length: 256
    },
    true,
    ["encrypt", "decrypt"]
  );
}

(2) CryptoJS

CryptoJS 是一个流行的 JavaScript 加密库,支持多种加密算法(如 AES、SHA、MD5 等)。

// 引入 CryptoJS
const CryptoJS = require("crypto-js");

// 加密
const secretKey = "my-secret-key-123"; // 密钥
const data = "Sensitive data";
const encrypted = CryptoJS.AES.encrypt(data, secretKey).toString();
console.log("Encrypted:", encrypted);

// 解密
const decrypted = CryptoJS.AES.decrypt(encrypted, secretKey).toString(CryptoJS.enc.Utf8);
console.log("Decrypted:", decrypted);

(3) jsrsasign

jsrsasign 是一个支持 RSA 和 ECC 的 JavaScript 加密库。

const KJUR = require("jsrsasign");

// 生成密钥对
const keyPair = KJUR.KEYUTIL.generateKeypair("RSA", 1024);
const publicKey = KJUR.KEYUTIL.getPEM(keyPair.pubKeyObj);
const privateKey = KJUR.KEYUTIL.getPEM(keyPair.prvKeyObj, "PKCS8PRV");

// 加密
const plainText = "Sensitive data";
const encrypted = KJUR.crypto.Cipher.encrypt(plainText, keyPair.pubKeyObj);
console.log("Encrypted:", encrypted);

// 解密
const decrypted = KJUR.crypto.Cipher.decrypt(encrypted, keyPair.prvKeyObj);
console.log("Decrypted:", decrypted);

3. 前端加密的应用场景

(1) 用户密码加密

const CryptoJS = require("crypto-js");

function hashPassword(password) {
  return CryptoJS.SHA256(password).toString(CryptoJS.enc.Hex);
}

const password = "user_password";
const hashedPassword = hashPassword(password);
console.log("Hashed Password:", hashedPassword);

(2) 数据传输加密

1、非对称加密传输密钥

// 客户端生成对称密钥
async function generateAndEncryptKey(publicKey) {
  const symmetricKey = await generateKey();
  
  // 使用服务器的公钥加密对称密钥
  const exportedKey = await window.crypto.subtle.exportKey('raw', symmetricKey);
  const encryptedKey = await window.crypto.subtle.encrypt(
    {
      name: "RSA-OAEP"
    },
    publicKey,
    exportedKey
  );
  
  return {
    encryptedKey: Array.from(new Uint8Array(encryptedKey)).join(','),
    symmetricKey
  };
}

2、完整传输流程

(3) 数据完整性校验

const CryptoJS = require("crypto-js");

const data = "Original data";
const hash = CryptoJS.SHA256(data).toString(CryptoJS.enc.Hex);

console.log("Generated Hash:", hash);

(4) 本地存储加密

// 使用Web Crypto API封装本地存储
const secureStorage = {
  async setItem(key, value, secretKey) {
    const encrypted = await encryptData(value, secretKey);
    localStorage.setItem(key, JSON.stringify(encrypted));
  },
  
  async getItem(key, secretKey) {
    const encryptedData = JSON.parse(localStorage.getItem(key));
    if (!encryptedData) return null;
    
    const decrypted = await decryptData(encryptedData, secretKey);
    return decrypted;
  }
};

// 使用示例
(async () => {
  const key = await generateKey();
  await secureStorage.setItem('user_data', JSON.stringify({name: 'John'}), key);
  const data = await secureStorage.getItem('user_data', key);
  console.log(data);
})();

4. 注意事项

总结 

到此这篇关于前端实现加密的常见方法和步骤的文章就介绍到这了,更多相关前端实现加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文