A .cer
file can be encoded using two different formats: PEM
and DER
.
If your file is encoded using the PEM
format, you could just use it like any other .pem
file (more info on that can be found in the Node.js documentation):
const https = require("https");
const options = {
key: fs.readFileSync("key.pem", "utf8"),
cert: fs.readFileSync("cert.cer", "utf8")
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end("Hello world");
}).listen(8000);
If your file's encoded using the DER
format, you first need convert it to a .pem
file using OpenSSL (the command was taken from here):
openssl x509 -inform der -in cert.cer -out cert.pem
and then can use the above code with the cert
filename being cert.pem
instead of cert.cer
:
const https = require("https");
const options = {
key: fs.readFileSync("key.pem", "utf8"),
cert: fs.readFileSync("cert.pem", "utf8")
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end("Hello world");
}).listen(8000);
In case you have the the key of the certificate authority that matches your cert.cer
file, you can include it in the options
argument of https.createServer
as following (the code example assumes the file is name ca.pem
and that it is encoded using the PEM
format):
const https = require("https");
const options = {
ca: fs.readFileSync("ca.pem", "utf8"),
key: fs.readFileSync("key.pem", "utf8"),
cert: fs.readFileSync("cert.pem", "utf8")
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end("Hello world");
}).listen(8000);
For more information about https.createServer
and its arguments, check out the documentation.
Note: all of the options above assume that you also have a public key encoded in the PEM
format named key.pem
and that the .cer
file is named cert.cer
. If you don't have a public key, please comment or add it to the question itself and I will update my answer accordingly.
If you're unsure which format your file's encoded in, you could try both options see which one works out for you.