首页 > 基础资料 博客日记
在 JavaScript 中实现数据加密与解密:Web Cryptography API 与 CryptoJS详解
2024-10-19 20:00:06基础资料围观495次
这篇文章介绍了在 JavaScript 中实现数据加密与解密:Web Cryptography API 与 CryptoJS详解,分享给大家做个参考,收藏Java资料网收获更多编程知识
在 JavaScript 中,可以使用 Web Cryptography API 或第三方库如 crypto-js 来实现加密和解密。本文将介绍如何使用这两种方法在客户端进行数据的加密和解密。

使用 Web Cryptography API
Web Cryptography API 是现代浏览器提供的一个强大、原生的加密 API。它允许在客户端进行加密、解密、签名和验证等操作。
生成密钥对
首先,生成一个 RSA 密钥对:
async function generateKeyPair() {
  const keyPair = await window.crypto.subtle.generateKey(
    {
      name: "RSA-OAEP",
      modulusLength: 2048,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256"
    },
    true,
    ["encrypt", "decrypt"]
  );
  const publicKey = await window.crypto.subtle.exportKey("spki", keyPair.publicKey);
  const privateKey = await window.crypto.subtle.exportKey("pkcs8", keyPair.privateKey);
  return {
    publicKey: publicKey,
    privateKey: privateKey
  };
}
generateKeyPair().then(keyPair => {
  console.log("Public Key:", arrayBufferToBase64(keyPair.publicKey));
  console.log("Private Key:", arrayBufferToBase64(keyPair.privateKey));
});
加密数据
使用公钥加密数据:
async function encryptData(data, publicKey) {
  const publicKeyBuffer = base64ToArrayBuffer(publicKey);
  const cryptoKey = await window.crypto.subtle.importKey(
    "spki",
    publicKeyBuffer,
    {
      name: "RSA-OAEP",
      hash: "SHA-256"
    },
    true,
    ["encrypt"]
  );
  const encodedData = new TextEncoder().encode(data);
  const encryptedData = await window.crypto.subtle.encrypt(
    {
      name: "RSA-OAEP"
    },
    cryptoKey,
    encodedData
  );
  return arrayBufferToBase64(encryptedData);
}
解密数据
使用私钥解密数据:
async function decryptData(encryptedData, privateKey) {
  const privateKeyBuffer = base64ToArrayBuffer(privateKey);
  const cryptoKey = await window.crypto.subtle.importKey(
    "pkcs8",
    privateKeyBuffer,
    {
      name: "RSA-OAEP",
      hash: "SHA-256"
    },
    true,
    ["decrypt"]
  );
  const encryptedBuffer = base64ToArrayBuffer(encryptedData);
  const decryptedData = await window.crypto.subtle.decrypt(
    {
      name: "RSA-OAEP"
    },
    cryptoKey,
    encryptedBuffer
  );
  return new TextDecoder().decode(decryptedData);
}
工具函数
用于在 ArrayBuffer 和 Base64 之间转换的工具函数:
function arrayBufferToBase64(buffer) {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}
function base64ToArrayBuffer(base64) {
  const binaryString = window.atob(base64);
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes.buffer;
}
使用 CryptoJS
crypto-js 是一个流行的 JavaScript 库,用于实现加密和解密。它支持多种加密算法,如 AES、DES、HMAC、SHA 等。
安装 CryptoJS
首先,安装 crypto-js:
npm install crypto-js
使用 AES 加密和解密
const CryptoJS = require('crypto-js');
// 加密数据
function encryptData(data, secretKey) {
  return CryptoJS.AES.encrypt(data, secretKey).toString();
}
// 解密数据
function decryptData(encryptedData, secretKey) {
  const bytes = CryptoJS.AES.decrypt(encryptedData, secretKey);
  return bytes.toString(CryptoJS.enc.Utf8);
}
const secretKey = 'my-secret-key';
const data = 'Hello, World!';
const encryptedData = encryptData(data, secretKey);
console.log('Encrypted Data:', encryptedData);
const decryptedData = decryptData(encryptedData, secretKey);
console.log('Decrypted Data:', decryptedData);
结论
通过本文,你可以了解如何在 JavaScript 中使用 Web Cryptography API 和 crypto-js 库进行数据的加密和解密。Web Cryptography API 提供了现代浏览器中的原生加密功能,而 crypto-js 则是一个功能强大的第三方库,适用于 Node.js 和浏览器环境。如果有任何问题或需要进一步的帮助,请在评论区留言或者联系我。
文章来源:https://blog.csdn.net/h_midnight/article/details/139391858
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:

