You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从CNG(BCrypt)RSA算法中提取公钥与私钥?

提取BCrypt生成的RSA密钥对方法

你当前的代码已经完成了RSA密钥对的生成与初始化,要提取公钥和私钥,核心是用BCryptExportKey函数,分别指定对应的密钥Blob类型即可。以下是完整的实现步骤和代码:

提取公钥

公钥需要导出为BCRYPT_RSAPUBLIC_BLOB格式,步骤如下:

  1. 调用BCryptExportKey传入NULL缓冲区,获取所需的内存大小
  2. 分配对应大小的内存缓冲区
  3. 再次调用BCryptExportKey完成公钥导出

提取私钥

私钥需要导出为BCRYPT_RSAPRIVATE_BLOB格式,步骤和公钥一致,仅Blob类型参数不同。

完整代码示例

#include <windows.h>
#include <bcrypt.h>
#include <iostream>
#include <vector>

#pragma comment(lib, "bcrypt.lib")

int main() {
    BCRYPT_ALG_HANDLE hAlg = NULL;
    BCRYPT_KEY_HANDLE hKey = NULL;
    NTSTATUS status = 0;

    // 打开RSA算法提供者
    status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_RSA_ALGORITHM, NULL, 0);
    if (status) { /* 后续补充错误处理 */ }

    // 生成密钥对
    status = BCryptGenerateKeyPair(hAlg, &hKey, 1024, 0);
    if (status) { /* 后续补充错误处理 */ }

    // 完成密钥对初始化
    status = BCryptFinalizeKeyPair(&hKey, 0);
    if (status) { /* 后续补充错误处理 */ }

    // -------------------------- 提取公钥 --------------------------
    DWORD cbPublicKey = 0;
    // 获取公钥所需缓冲区大小
    status = BCryptExportKey(hKey, NULL, BCRYPT_RSAPUBLIC_BLOB, NULL, 0, &cbPublicKey, 0);
    if (status) { /* 后续补充错误处理 */ }

    std::vector<BYTE> publicKey(cbPublicKey);
    // 导出公钥
    status = BCryptExportKey(hKey, NULL, BCRYPT_RSAPUBLIC_BLOB, publicKey.data(), cbPublicKey, &cbPublicKey, 0);
    if (status) { /* 后续补充错误处理 */ }
    std::cout << "公钥导出成功,大小:" << cbPublicKey << "字节" << std::endl;

    // -------------------------- 提取私钥 --------------------------
    DWORD cbPrivateKey = 0;
    // 获取私钥所需缓冲区大小
    status = BCryptExportKey(hKey, NULL, BCRYPT_RSAPRIVATE_BLOB, NULL, 0, &cbPrivateKey, 0);
    if (status) { /* 后续补充错误处理 */ }

    std::vector<BYTE> privateKey(cbPrivateKey);
    // 导出私钥
    status = BCryptExportKey(hKey, NULL, BCRYPT_RSAPRIVATE_BLOB, privateKey.data(), cbPrivateKey, &cbPrivateKey, 0);
    if (status) { /* 后续补充错误处理 */ }
    std::cout << "私钥导出成功,大小:" << cbPrivateKey << "字节" << std::endl;

    // 清理资源
    if (hKey) BCryptDestroyKey(hKey);
    if (hAlg) BCryptCloseAlgorithmProvider(hAlg, 0);

    return 0;
}

关键说明

  • BCRYPT_RSAPUBLIC_BLOB:Windows定义的公钥二进制格式,包含RSA的模数、公钥指数等核心信息
  • BCRYPT_RSAPRIVATE_BLOB:对应私钥格式,包含模数、指数、私钥专属参数(如p、q、d等)
  • 导出完成后,可将缓冲区数据保存为文件,若需转换为PEM等通用格式,需自行处理Blob结构与编码规则

内容的提问来源于stack exchange,提问作者B00t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:55:45