利用crypto.subtle.generateKey()写公钥和私钥,并用exportKey将公私钥导出

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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值