使用pem库生成带v3_req扩展的证书时报v3_req扩展段加载错误
报错原因
- 路径拼写错误:你代码中填写的
_dirname为单下划线,Node.js 内置的用于获取当前脚本所在目录的变量是双下划线的__dirname,拼写错误会导致扩展配置文件路径解析失败,openssl 读取不到正确的配置文件内容,自然找不到v3_req段。 - 参数冲突:你同时传入了
config: {}和extFile两个参数,根据 pem 库的逻辑,只要指定了config参数,库会自动基于该配置生成临时 openssl 配置文件,直接忽略你传入的extFile路径,你传入的空config对象生成的配置里没有v3_req段,所以触发报错。 - 命令逻辑匹配问题:就算
extFile正常加载,openssl x509 -req命令指定-extensions v3_req时,要求扩展配置文件中必须存在独立的[v3_req]段,虽然你编写的配置里有该段,但前面两个问题导致配置没有被正确加载,所以触发报错。
修复方案
- 修正路径拼写,把
_dirname改成__dirname - 删除
config: {}参数,避免 pem 忽略你自定义的 extFile 配置 - 如果你需要保留
config参数,可以直接把 v3_req 配置写到 config 对象中,无需额外传 extFile,示例如下:
const cert = await pem.createCertificate({ clientKey: clientPrivateKey, serviceKey: servicePrivateKey, selfSigned: true, csr, days: 1095, config: { req: { req_extensions: 'v3_req', distinguished_name: 'req_distinguished_name' }, req_distinguished_name: { commonName: 'Common Name', commonName_max: 64 }, v3_req: { basicConstraints: 'critical,CA:TRUE', keyUsage: 'nonRepudiation, digitalSignature, keyEncipherment' } } });
内容的提问来源于stack exchange,提问作者bmagnette
相关产品推荐
相关产品推荐

