在 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