generateAndExportKeyPair:生成 RSA 密钥对并导出为 PEM 格式。
importPublicKey 和 importPrivateKey:将 PEM 格式的密钥字符串转换为二进制格式,并使用 crypto.subtle.importKey() 导入。
crypto.subtle.importKey:导入密钥的函数,需要指定密钥格式(“spki” 或 “pkcs8”)、密钥材料、算法参数、是否可导出以及密钥的用途(如 “encrypt” 或 “decrypt”)。
注意事项:
确保你的环境支持 Web Crypto API,通常现代浏览器都支持。
密钥生成、导出和导入都是异步操作,需要使用 async/await 或 .then() 和 .catch() 来处理。
密钥材料不应该以明文形式打印或存储。示例中的 console.log 只是为了演示目的。
//keyGenParams生成密钥的一些参数
const keyGenParams={
name:'RSA-OAEP',
modulusLength:2048,
publicExponent:new Uint8Array([1,0,1]),
hash:{name:"SHA-256"}
};
//generateAndExportKeyPair()异步函数生成密钥对
async function generateAndExportKeyPair()
{
try{
const keyPair=await crypto.subtle.generateKey(keyGenParams,true,["encrypt","decrypt"]);
const exportedPublicKey=await crypto.subtle.exportKey("spki",keyPair.publicKey);
const publicKeyPem=window.btoa(String.fromCharCode(...new Uint8Array(exportedPublicKey)));
const exportedPrivateKey=await crypto.subtle.exportKey("pkcs8",keyPair.privateKey);
const privateKeyPem=window.btoa(String.fromCharCode(...new Uint8Array(exportedPrivateKey)));
console.log("私钥:",privateKeyPem);
console.log("公钥:",publicKeyPem);
return {publicKeyPem,privateKeyPem};
}catch(error)
{
console.error("error generating or exporting keys:",error);
}
}
//generateAndExportKeyPair();
//console.log(generateAndExportKeyPair().then(console.log));
//异步函数importPublickKey()导入公钥
async function importPublickKey(pem)
{
const binaryKey=Uint8Array.from(atob(pem),(c)=>c.charCodeAt(0));
console.log(binaryKey);
const importedPublicKey=await crypto.subtle.importKey(
"spki",
binaryKey,
{name:"RSA-OAEP",hash:{name:'SHA-256'}},
true,
["encrypt"]
);
console.log("公钥导入成功");
return importedPublicKey;
}
//异步函数importPrivateKey()导入私钥
async function importPrivateKey(pem)
{
const binaryKey=Uint8Array.from(atob(pem),(c)=>c.charCodeAt(0));
const importedPrivateKey=await crypto.subtle.importKey(
"pkcs8",
binaryKey,
{name:'RSA-OAEP',hash:{name:'SHA-256'}},
true,
["decrypt"]
);
console.log("私钥导入成功");
return importedPrivateKey;
}
//导步函数init()执行导入公私钥,因为generateAndExportKeyPair()返回的是一个期约,所以必须包含在异步函数内
async function init(){
let key=await generateAndExportKeyPair().then((res)=>{
return res;
});
const importedpKey=await importPublickKey(key.publicKeyPem);
const importedPrivateKey=await importPrivateKey(key.privateKeyPem);
}
init();