Generate private key and certificate for https with NodeJS

Create a new directory and install npm module pem

$ mkdir -p /root/userdir/keys
$ mkdir -p /root/userdir/node_modules
$ cd /root/userdir/node_modules
$ npm i pem
$ touch /root/userdir/generatepem.js
$ cd /root/userdir

Edit the file /root/userdir/generatepem.js with this content:

var fs = require("fs");
var pem = require("pem");

pem.createCertificate({days: 365, selfSigned: true}, function(err, keys) {
    fs.writeFile("/root/userdir/keys/privatekey.pem", keys.serviceKey);
    fs.writeFile("/root/userdir/keys/certificate.pem", keys.certificate);
});

Generate the files:

$ node /root/userdir/generatepem.js

You’ve gotten now privatekey.pem and certificate.pem into the keys directory. You can copy now copy/cut paste anywhere you need !

I need to add an SSL certificate to thethingbox to do https calls (for 2.3.5 or later).

You can find info at

http://nodered.org/docs/configuration.html
https://github.com/node-red/node-red/blob/master/settings.js

To activate the Node-RED option “https”, you have to uncomment this on the file /root/thethingbox/node_modules/node-red/settings.js

// https: {
//     key: fs.readFileSync('privatekey.pem'),
//     cert: fs.readFileSync('certificate.pem')
// },

Then, you have to uncomment // var fs = require("fs"); on the top of the settings.js file. Replace privatekey.pem and certificate.pem by the path of yours.

To use https, you also have to set the port to 443, for this, edit the file /root/thethingbox/thethingbox.js : replace var PORT = 80 by var PORT = 443

Then, restart : $ service thethingbox restart

Back to top