使用 WebCrypto API 从私钥生成公钥 [英] Generate Public key from Private Key using WebCrypto API
本文介绍了使用 WebCrypto API 从私钥生成公钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用
I'm using Web Crypto API and am generating RSA Keypair using generateKey function. Because of some bugs in my code, I have deleted public key for some users. I'm wondering if there is any way to generate public key out of private key? I know that it's easily doable for ssh keys. Here is my sample code for generating RSA key pair:
const generateRSAKeys = (): Promise<CryptoKeyPair> => {
return crypto.subtle.generateKey(
{
name: 'RSA-OAEP',
modulusLength: 2048
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-512' },
},
true,
['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'],
);
解决方案
You can do it by exporting private key and importing exported data like public data
const keys = await crypto.subtle.generateKey(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-512' },
},
true,
['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'],
);
// export private key to JWK
const jwk = await crypto.subtle.exportKey("jwk", keys.privateKey);
// remove private data from JWK
delete jwk.d;
delete jwk.dp;
delete jwk.dq;
delete jwk.q;
delete jwk.qi;
jwk.key_ops = ["encrypt", "wrapKey"];
// import public key
const publicKey = await crypto.subtle.importKey("jwk", jwk, { name: "RSA-OAEP",
hash: "SHA-512" }, true, ["encrypt", "wrapKey"]);
console.log(publicKey)
这篇关于使用 WebCrypto API 从私钥生成公钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文