Node.js - HTTPS PFX Error: Unable to load BIO

Node.js - HTTPS PFX Error: Unable to load BIO

我正在尝试做出 HTTPS 请求承诺。我已经知道 PFX 很好,这不是问题(我有一个类似的示例应用程序在工作)。

我正在做以下事情:

var request = require('request-promise');

...

options.pfx = fs.readFileSync('myfile.pfx');
options.passphrase = 'passphrase';

我正在将我的选项传递到请求中。

request.post(options);

然后我尝试构建请求,但出现以下错误:

_tls_common.js:130
  c.context.loadPKCS12(pfx, passphrase);
            ^

Error: Unable to load BIO
at Error (native)
at Object.createSecureContext (_tls_common.js:130:17)
at Object.exports.connect (_tls_wrap.js:955:21)
at Agent.createConnection (https.js:73:22)
at Agent.createSocket (_http_agent.js:174:16)
at Agent.addRequest (_http_agent.js:143:23)
at new ClientRequest (_http_client.js:133:16)
at Object.exports.request (http.js:31:10)
at Object.exports.request (https.js:163:15)
at Request.start (/Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:747:30)
at Request.write (/Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:1369:10)
at end (/Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:561:16)
at Immediate._onImmediate (/Users/filomeno/workspace/sla-crawler/node_modules/request/request.js:589:7)
at processImmediate [as _immediateCallback] (timers.js:374:17)

我有一个示例应用程序,其中可以使用相同的代码。 我尝试转换为 .p12 但没有成功。

有谁知道这个错误可能指的是什么?

编辑: 我正在使用 lodash 合并 2 个具有动态属性和静态属性的对象

_.merge(options, _this.requestOptions);

这就是导致问题的原因

查看nodejs源码(具体是这个文件https://github.com/nodejs/node/blob/master/src/node_crypto.cc

这个函数抛出错误

// Takes .pfx or .p12 and password in string or buffer format
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
   Environment* env = Environment::GetCurrent(args);
   ...

第 964 行

in = LoadBIO(env, args[0]);
if (in == nullptr) {
   return env->ThrowError("Unable to load BIO");
}

其中LoadBIO returns null

// Takes a string or buffer and loads it into a BIO.
// Caller responsible for BIO_free_all-ing the returned object.
static BIO* LoadBIO(Environment* env, Local<Value> v) {
  HandleScope scope(env->isolate());

  if (v->IsString()) {
    const node::Utf8Value s(env->isolate(), v);
    return NodeBIO::NewFixed(*s, s.length());
  }

  if (Buffer::HasInstance(v)) {
    return NodeBIO::NewFixed(Buffer::Data(v), Buffer::Length(v));
  }

  return nullptr;
}

也许缓冲区不知何故不可读?此外,该函数似乎需要一个 utf-8 编码的字符串。

一些想法:

您确定文件路径正确吗?

可能是编码问题?您是否尝试明确设置 fs.readFileSync() 编码?

试试 fs.readFile(<filename>, <encoding>, function(error, data){}) 看看会不会报错?