crypto.subtle.generateKey 需要在支持 Web Crypto API 的环境中运行,比如现代浏览器,或在nodejs环境当中
密钥生成和导出操作是异步的,因此需要使用 async/await 或者 .then() 和 .catch() 来处理。
generateKey 函数的第三个参数是一个数组,指定了密钥对的使用方式,这里我们指定了 “encrypt” 和 “decrypt”。
exportKey 函数的第一个参数决定了密钥的导出格式,“spki” 用于公钥,“pkcs8” 用于私钥。
出于安全考虑,密钥材料不应该以明文形式打印或存储。示例中的 console.log 只是为了演示目的。
const keyGenParams={
name:'RSA-OAEP',//算法名称
modulusLength:2048,//密钥长度
publicExponent:new Uint8Array([1,0,1]),//公钥的指数65537最大值
hash:{name:"SHA-256"}//使用SHA-256算法
};
async function generateAndExportKeyPair()
{
try{
//利用generateKey()生成一个公私密钥
const keyPair=await crypto.subtle.generateKey(keyGenParams,true,["encrypt","decrypt"]);
//“spki” 表示导出公钥
const exportedPublicKey=await crypto.subtle.exportKey("spki",keyPair.publicKey);
//window.btoa是浏览器方法用于创建一个 base-64 编码的字符串。
const publicKeyPem=window.btoa(String.fromCharCode(...new Uint8Array(exportedPublicKey)));
//pkcs8是表示导出私钥
const exportedPrivateKey=await crypto.subtle.exportKey("pkcs8",keyPair.privateKey);
const privateKeyPem=window.btoa(String.fromCharCode(...new Uint8Array(exportedPrivateKey)));
console.log("私钥:",privateKeyPem);
console.log("公钥:",publicKeyPem);
}catch(error)
{
console.error("error generating or exporting keys:",error);
}
}
generateAndExportKeyPair();