使用 window.crypto.subtle
,可以实现非对称加密(也称为公钥加密)。非对称加密使用一对密钥:公钥用于加密数据,私钥用于解密数据。以下是一个示例,演示如何使用 window.crypto.subtle
实现非对称加密和解密:
生成密钥对
首先,生成一个 RSA 密钥对:
async function generateKeyPair() {
return await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048, // 可以是 2048 或更高
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true, // 是否可导出
["encrypt", "decrypt"] // 使用密钥的操作
);
}
加密数据
使用公钥加密数据:
async function encryptData(publicKey, data) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(data);
return await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP",
},
publicKey,
encodedData
);
}
解密数据
使用私钥解密数据:
async function decryptData(privateKey, encryptedData) {
const decryptedData = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP",
},
privateKey,
encryptedData
);
const decoder = new TextDecoder();
return decoder.decode(decryptedData);
}
完整示例
(async () => {
// 生成密钥对
const keyPair = await generateKeyPair();
const publicKey = keyPair.publicKey;
const privateKey = keyPair.privateKey;
// 加密数据
const data = "Hello, World!";
const encryptedData = await encryptData(publicKey, data);
console.log("Encrypted Data:", new Uint8Array(encryptedData));
// 解密数据
const decryptedData = await decryptData(privateKey, encryptedData);
console.log("Decrypted Data:", decryptedData);
})();
注意事项
- 密钥管理:公钥和私钥必须妥善管理。公钥可以公开,但私钥必须保密。
- 性能:非对称加密比对称加密慢得多,因此适用于加密小数据或加密对称密钥。
- 错误处理:在加密和解密过程中,应正确处理可能的错误。
通过上述步骤,你可以在前端应用中使用 window.crypto.subtle
实现非对称加密和解密。不过,通常情况下,非对称加密操作应该与后端配合使用,确保整体系统的安全性。前端主要负责传输加密数据,而敏感数据的加密和解密操作最好在服务器端完成。
前端工程师、程序员