【问题标题】:Setting Up HTTPS in Express JS在 Express JS 中设置 HTTPS
【发布时间】:2019-12-04 08:53:31
【问题描述】:

我从托管服务提供商处购买了 AlphaSSL。他们只是给了我

  • domain.csr.crt
  • domain.interCert.crt
  • domain.PKCS7Cert.crt
  • domain.rootCert.crt
  • domain.X509Cert.crt

但据我所知,要使用 Express 在 Node.JS 上运行 HTTPS,我至少需要密钥文件和证书文件。那么,我应该使用什么样的文件呢?谢谢。

【问题讨论】:

  • 你有密钥文件吗?
  • @TienDuong 不,我没有。托管服务提供商只需给我那些证书文件。

标签: javascript node.js express https


【解决方案1】:

您需要一个私钥和一个证书文件,这是一个简单的 Node.js 中的 HTTPS 服务器示例,您可以看到我们需要同时加载私钥和证书文件。如果您有一个 .pfx 文件,它可能同时包含证书私钥。也检查一下这个问题,您可能在 .crt 文件之一中拥有私钥:How do I identify if my certificate contains private key?

使用私钥和证书的示例:

const fs = require('fs');
const https = require('https');
const privateKey  = fs.readFileSync('./privateKey.key', 'utf8');
const certificate = fs.readFileSync('./certificate.crt', 'utf8');

const credentials = { key: privateKey, cert: certificate };
const express = require('express');
const app = express();

// Add test route here. 
app.get("/test", (req, res) => {
    res.status(200).send("All good");
})

const server = https.createServer(credentials, app);
server.listen(8443);

使用 .pfx 文件:

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

const options = {
  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
  passphrase: 'sample'
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);

(来自 Node.js 文档的示例:Https Example

【讨论】:

    【解决方案2】:

    您可以对所有这些文件做的一件事是使用 Nodepad 打开它们,然后尝试计算 keycert,如下所示:

    私钥(密钥选项):

    应该有字符串:-----BEGIN RSA PRIVATE KEY-----

    公钥(证书选项):

    应该有字符串-----BEGIN CERTIFICATE-----

    注意:

    如果你找到多个public keys,我会选择domain.X509Cert.crtdomain.PKCS7Cert.crt(PK 代表公钥)。

    至于domain.rootCert.crt,安装在你的系统服务器(不是expressjs服务器)上。

    PS:扩展并不重要

    【讨论】:

    • 其中没有一个包含私钥。它们只是 PKCS7、证书和证书请求。
    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 2021-07-07
    • 2021-10-15
    • 1970-01-01
    • 2012-06-13
    • 2013-04-19
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多