首页 > 解决方案 > 使用 WebCrypto API 从私钥生成公钥

问题描述

我正在使用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'],
);

标签: javascriptencryptionrsaencryption-asymmetricwebcrypto-api

解决方案


您可以通过导出私钥并导入导出的数据(如公共数据)来做到这一点

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)

在此处输入图像描述


推荐阅读