用Google Chrome 浏览器的Web Crypto API生成RSA密钥对:在浏览器环境中生成一对2048位的RSA密钥(公钥+私钥),然后以JSON格式(JWK)将它们打印到控制台,方便开发者查看和使用。
// 控制台生成密钥对
(async () => {
// 调用Web Crypto API生成密钥对
const pair = await crypto.subtle.generateKey(
{
// 指定使用RSA PKCS#1 v1.5签名算法
name: "RSASSA-PKCS1-v1_5",
// RSA模数长度为2048位
modulusLength: 2048,
// 公钥指数65537(0x010001)
publicExponent: new Uint8Array([1, 0, 1]),
// 使用SHA-256哈希算法
hash: "SHA-256",
},
// 表示密钥可导出
true,
// 密钥用途:私钥用于签名,公钥用于验证
["sign", "verify"]
);
console.log("=== private key ===");
console.log(
JSON.stringify(
// 将私钥导出为JWK(JSON Web Key)格式并格式化输出
await crypto.subtle.exportKey("jwk", pair.privateKey),
null,
" "
)
);
console.log("=== public key ===");
console.log(
JSON.stringify(
await crypto.subtle.exportKey("jwk", pair.publicKey),
null,
" "
)
);
})();