使用 WebCrypto API 从私钥生成公钥

Moh*_*lam 7 javascript encryption rsa encryption-asymmetric 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'],
);
Run Code Online (Sandbox Code Playgroud)

小智 7

您可以通过导出私钥并导入导出的数据(如公共数据)来实现

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我该如何针对 ECDSA 进行调整? (5认同)
  • 对于 ECDSA 段[此处](/sf/answers/5050775971/)。 (2认同)