简体   繁体   中英

Setting Up HTTPS in Express JS

I bought an AlphaSSL from a hosting provider. They just gave me

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

But as I know that to run HTTPS on Node.JS using Express, I need at least key file and cert file. Then, what kind of file I should use? Thank you.

You'll need a private key and a certificate file, here's a simple example of an HTTPS server in Node.js, you can see we need to load both the private key and certificate files. If you have a .pfx file this may contain both the certificate and the private key. Check this question out as well, you may have the private key in one of the .crt files: How do I identify if my certificate contains private key?

Example using private key and cert:

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);

Using .pfx file:

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);

(Example from Node.js docs: Https Example )

One thing you can do with all those files is to open them with Nodepad, and try to figure the key and cert as follows:

Private Key (key option):

Should have the string: -----BEGIN RSA PRIVATE KEY-----

Public Key (cert option):

Should have the string -----BEGIN CERTIFICATE-----

Note:

If you find multiple public keys , i would go with domain.X509Cert.crt or domain.PKCS7Cert.crt (PK stands for Public Key).

As for domain.rootCert.crt , install it on your system server (not expressjs server).

PS: Extensions don't matter that much

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM