javascript - 使用 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'],
);
解决方案
您可以通过导出私钥并导入导出的数据(如公共数据)来做到这一点
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)
推荐阅读
- java - 将一天添加到一个日历变量会影响其他变量
- java - Android 中 AudioPresentation 类有什么用?
- typescript - Angular 7 Http 获取请求发送对象作为参数
- php - Google MyBusiness PHP Api OpenSSL SSL_connect: SSL_ERROR_SYSCALL
- php - 使用数据库中的值突出显示 HTML 表格单元格
- javascript - 如何在单个 html 文件中构建 Angular 应用程序,并将所有脚本内联?
- excel - 循环工作表
- python - 将元组列表重塑为 3D 数组
- odoo - 在odoo sh中更改版本后自动更新模块不起作用
- angular - 仅在第一次失败时执行第二次 http 调用