Reputation: 1568
I want to run an https server. I found this code online :
var fs = require('fs'),
http = require('http'),
https = require('https'),
express = require('express');
var port = 8000;
var options = {
key: fs.readFileSync('./ssl/privatekey.pem'),
cert: fs.readFileSync('./ssl/certificate.pem'),
};
var app = express();
var server = https.createServer(options, app).listen(port, function(){
console.log("Express server listening on port " + port);
});
app.get('/', function (req, res) {
res.writeHead(200);
res.end("hello world\n");
});
the problem is that i do not know how to create those files. is there a way of generating them using the node shell? (working on Windows)
Upvotes: 5
Views: 13301
Reputation: 56
Take a look at this: How to create .pem files for https web server
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
If you have openSSL installed you should be able to type this command directly into the command prompt on windows or terminal on mac.
Upvotes: 4
Reputation: 2646
import crypto from 'crypto'
import { writeFileSync } from 'fs';
const certKey = crypto.randomBytes(1024).toString('hex')
const certKeyFormatted = certKey.match(/.{1,64}/g).join("\n")
const certContents =
'-----BEGIN CERTIFICATE-----' + "\n" +
certKeyFormatted + "\n" +
'-----END CERTIFICATE-----'
console.log('generated certificate')
console.log()
console.log(certContents)
const filePath = 'signingKey.pem'
writeFileSync(
filePath,
certContents,
{ encoding: 'utf8' }
);
console.log()
console.log('certificate saved to', filePath)
this gives something like
-----BEGIN CERTIFICATE-----
018bd0f56deb8f3695e9bcc73b8031829b4505a6b49257e41a5597743135473a
34ca92304cbb293ea05d3a5e8fff497d32e398196f8c94def68a3333bec3343e
3248a97e3af7d1ae69e8993c9a2d0d0770ddc0694267a63be241c18204363074
84542b3205a06a05d05607944492c914f04f630a93efdb1d5fec796071951a7c
...
67ea551c13af07d6f3fcefdd6d2f17e4aa084b9c82254a52d2903791e31418cf
5d9f07137c5188fa26ac480b9c7c25ca6dd7c1464a3bcc53294d84770ad995a4
efa357956865134e97ec02a172111d4a0db68f63cb3f68d1438fe03bef55f937
ee5d60af45a53f8cd43e8ce6ea26d75ff09714468914274443e581acf1c96bb5
-----END CERTIFICATE-----
Upvotes: 1