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

无法将NodeJS生成的公钥通过Windows CNG API加载

RSA公钥加载失败问题解决

错误原因

Windows CNG API的CryptDecodeObjectEx接口默认仅支持**PKCS#8(SubjectPublicKeyInfo)**格式的公钥,你当前用Node.js生成的是PKCS#1格式的RSA公钥,两者ASN.1结构存在差异,导致解析时触发0x8009310b(ASN1标签值错误)。

解决方法

修改Node.js代码中publicKeyEncoding的type参数为spki(对应PKCS#8标准公钥格式),生成CNG兼容的公钥:

const crypto = require('crypto');
const fs = require('fs');

crypto.generateKeyPair(
    "rsa",
    {
        modulusLength: 1024,
        publicKeyEncoding: {
            type: "spki", // 替换原pkcs1为spki
            format: "pem",
        },
        privateKeyEncoding: {
            type: "pkcs1", // 私钥格式可保留PKCS#1,CNG加载私钥时通常兼容
            format: "pem",
        },
    },
    (err, publicKey, privateKey) => {
        if (err) throw err;
        fs.writeFileSync("/home/dev/priv.pem", privateKey);
        fs.writeFileSync("/home/dev/pub.pem", publicKey);
    }
);

备选方案(已有PKCS#1公钥转换)

如果已经生成了PKCS#1格式的公钥,可通过OpenSSL将其转换为PKCS#8格式:

openssl rsa -pubin -in pub.pem -outform PEM -pubout -out pub_spki.pem

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:12:45