我正在使用Web Crypto API,并正在使用generateKey函数生成RSA密钥对。由于我的代码中存在一些错误,因此我为某些用户删除了公钥。我想知道是否有任何方法可以从私钥中生成公钥?我知道使用ssh键很容易。这是我用于生成RSA密钥对的示例代码:
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'],
);
答案 0 :(得分:0)
您可以通过导出私钥并导入导出的数据(例如公共数据)来实现此目的
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)