Generating an SSL Key to work with node.js - node.js

I'm working to setup a SSL via GoDaddy to use with my node.js server on AWS EC2. I've been unable to get it to work.
Here's what I've tried:
Intended for the domain: files.mysite.com
On the server I run:
$ openssl req -new -newkey rsa:2048 -nodes -keyout files.mysite.key -out files.mysite.csr
Common Name: files.mysite.com
password: left empty
I then get the CSR: vim files.mysite.csr
I copy and paste from:
-----BEGIN CERTIFICATE-----
......... lots of stuff
-----END CERTIFICATE-----
There is an extra empty line at the end, which I leave and paste into the GoDaddy interface using rekey.
I then download the godaddy key which provides:
gd_bundle.crt
files.mysite.com.crt
Then in node I insert:
key: fs.readFileSync('server.key').toString(),
cert: fs.readFileSync('server.crt').toString()
I'm not sure what server.key is or server.crt given that GoDaddy provides two crt files?
Can you help?

GoDaddy uses an intermidiate certificate to sign your certificate. This has several advantages to both you and GoDaddy. But it takes a bit more work to get it to work (just a bit, mostly googling around).
In node.js you can install them like this:
require('https').createServer({
key: fs.readFileSync('files.mysite.com.key'),
cert: fs.readFileSync('files.mysite.com.crt'),
ca: [fs.readFileSync('gd_bundle.crt')] // <----- note this part
}, app).listen(443);

You should use .crt and .key files at the creation of your http server instance. The following snippet will give you the idea :
require('https').createServer({
key: fs.readFileSync('/path/to/something.key'),
cert: fs.readFileSync('/path/to/something.crt'),
}, app).listen(443);
If you have a passphrase for your key, you can pass it though as follows :
require('https').createServer({
key: fs.readFileSync('/path/to/something.key'),
cert: fs.readFileSync('/path/to/something.crt'),
passphrase: 'your_secret_passpahrase'
}, app).listen(443);

Related

net::ERR_CERT_AUTHORITY_INVALID (React with Node)

Please Help, I'm in a big trouble.
Actually, I'm learning Full Stack Web Development with React on Coursera.
I created the private key and certificate by typing the following at the prompt:
openssl genrsa 1024 > private.key
openssl req -new -key private.key -out cert.csr
openssl x509 -req -in cert.csr -signkey private.key -out certificate.pem
These above commands created 3 files on the given location :- private.key, certificate.pem and cert.csr
And then i included this in www file:-
var options = {
key: fs.readFileSync(__dirname+'/private.key'),
cert: fs.readFileSync(__dirname+'/certificate.pem')
};
var secureServer = https.createServer(options,app);
After Integrating both React Client and Server, i was able to run my react app on Browser.
But when i tried to access the React app using the Network IP address, it stops fetching data from server and on console i found this error message - net::ERR_CERT_AUTHORITY_INVALID
Please help, As i said i'm learning. I have no idea about this.

SOAP request in Node using SSL

Recently, I've been working with SOAP requests.
I've managed to use the node-soap module to be able to send successful requests to http services. However, now I want to use it to send a request to an external https web service.
I have managed to send SSL requests using a .cer file with cUrl. But when trying this in the node.js code, I am getting errors. From what I have read (see ClientSSLSecurity on the node-soap module), I need a key (in .key format) and a certificate (in .pem format). I do not know whether this requires a private key or not? I have managed to extract a public key from my .cer file.
I have tried the below code:
var createSoapClient = function (){
soap.createClient(url, function(err,client){
client.setSecurity(new soap.ClientSSLSecurity(
'mycert.cer',
'pubkey.key'
));
if(err)
console.error(err);
else {
client.MyOperation(args,function(err,response){
if(err){
console.error(err);
}
else{
console.log(response);
}
})
}
});
}
however, this results in the below error message:
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
What am I missing? Is it a private key?
Thank you!
According to package found on npm, regarding ClientSSLSecurity :
https://www.npmjs.com/package/axl-node-soap
https://www.npmjs.com/package/soap-x509
https://www.npmjs.com/package/strong-soap#clientsslsecurity
https://www.npmjs.com/package/soap#clientsslsecurity
I assume that you've pass wrong argument to ClientSSLSecurity. It seems to take the key then the certificate, you're passing the certificate then the key.
Try to do something like this :
client.setSecurity(new soap.ClientSSLSecurity(
'pubkey.key',
'mycert.cer'
));
Which package are you using ?
You're couple key/cert is probably wrong
Try to regenerate the certificate :
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt
then pass key.pem as the key and server.crt as the certificate.

How to create HTTPS cert for ExpressJS app?

This is how I generate a self-signed certificate, following this guide:
$ openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem
In my code, in bin/www:
var options = {
key: fs.readFileSync('ssl/key.pem'),
cert: fs.readFileSync('ssl/cert.pem'),
passphrase: 'xxxx'
};
I will get a warning on Chrome:
Your connection is not private
If I use it over an iframe:
<iframe src="https://127.0.1.1:3030/" width="100%" height="900" frameborder="1"></iframe>
Then I will get this error on Chrome:
GET https://127.0.1.1:3030/ net::ERR_INSECURE_RESPONSE
How can I create the certificate properly without having these warning and error?
Notes:
There is accepted answer from that suggestion.Also most of the answers are for Windows. I am on Linux/ Ubuntu/ Arch.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Trying to follow various instructions on creating a self-signed cert for use with localhost, Most of the instructions seem to be for IIS, but I'm trying to use Nodejs/Express. None of them work properly because while the cert gets installed, it is not trusted. here's what I've tried that fails:
How can I create a self-signed cert for localhost?
https://www.digitalocean.com/community/articles/how-to-create-a-ssl-certificate-on-nginx-for-ubuntu-12-04/
http://blogs.developerforce.com/developer-relations/2011/05/generating-valid-self-signed-certificates.html
http://www.robbagby.com/iis/self-signed-certificates-on-iis-7-the-easy-way-and-the-most-effective-way/
Can someone offer a workflow that can do this? I can get a cert installed, but I can't get the cert to be trusted in either chrome (v32) or IE (v10).
EDIT: it was suggested in comments that the problem is no trusted cert-root. I installed the cert via IE but it's still not being trusted.
The answers above were partial. I've spent so much time getting this working, it's insane. Note to my future self, here is what you need to do:
I'm working on Windows 10, with Chrome 65. Firefox is behaving nicely - just confirm localhost as a security exception and it will work. Chrome doesn't:
Step 1. in your backend, create a folder called security. we will work inside it.
Step 2. create a request config file named req.cnf with the following content (credit goes to: #Anshul)
req.cnf :
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = Country initials like US, RO, GE
ST = State
L = Location
O = Organization Name
OU = Organizational Unit
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = #alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost
An explanation of this fields is here.
Step 3. navigate to the security folder in the terminal and type the following command :
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256
Step 4. then outside of security folder, in your express app do something like this: (credit goes to #Diego Mello)
backend
/security
/server.js
server.js:
const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000
app.get('/', (req, res) => {
res.send("IT'S WORKING!")
})
const httpsOptions = {
key: fs.readFileSync('./security/cert.key'),
cert: fs.readFileSync('./security/cert.pem')
}
const server = https.createServer(httpsOptions, app)
.listen(port, () => {
console.log('server running at ' + port)
})
Step 5. start the server, node server.js, and go to https://localhost:3000.
At this point we have the server setup. But the browser should show a warning message.
We need to register our self-signed certificate, as a CA trusted Certificate Authority, in the chrome/windows certificates store. (chrome also saves this in windows,)
Step 6. open Dev Tools in chrome, go to Security panel, then click on View Certificate.
Step 7. go to Details panel, click Copy File, then when the Certificate Export Wizard appears, click Next as below:
Step 8. leave DER encoding, click next, choose Browse, put it on a easy to access folder like Desktop, and name the certificate localhost.cer, then click Save and then Finish.. You should be able to see your certificate on Desktop.
Step 9. Open chrome://settings/ by inserting it in the url box. Down below, click on Advanced / Advanced Options, then scroll down to find Manage Certificates.
Step 10. Go to Trusted Root Certification Authorities panel, and click import.
We will import the localhost.cer certificate we just finished exporting in step 8.
Step 11. click browse, find the localhost.cer, leave the default values click next a bunch of times - until this warning appears, click yes.
Step 12. close everything, and restart chrome. Then, when going to https://localhost:3000 you should see:
Shortest way.
Tested on MacOS, but may work similarly on other OS.
Generate pem
> openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
> openssl rsa -in keytmp.pem -out key.pem
Your express server
const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000
app.get('/', (req, res) => {
res.send('WORKING!')
})
const httpsOptions = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem')
}
const server = https.createServer(httpsOptions, app).listen(port, () => {
console.log('server running at ' + port)
})
Open https://localhost:3000 in Google Chrome and you'll see that it's not secure. Yet!
In Developer Tools > Security > View Certificate: Drag image to your desktop and double click it.
Click 'Add'
Find it in Keychain Access and double click it
Expand 'Trust' and change 'When using this certificate' to 'Always trust'.
You may be prompted to authenticate.
Restart your server.
Refresh your browser.
Enjoy! :)
You can try openSSL to generate certificates.
Take a look at this.
You are going to need a .key and .crt file to add HTTPS to node JS express server. Once you generate this, use this code to add HTTPS to server.
var https = require('https');
var fs = require('fs');
var express = require('express');
var options = {
key: fs.readFileSync('/etc/apache2/ssl/server.key'),
cert: fs.readFileSync('/etc/apache2/ssl/server.crt'),
requestCert: false,
rejectUnauthorized: false
};
var app = express();
var server = https.createServer(options, app).listen(3000, function(){
console.log("server started at port 3000");
});
This is working fine in my local machine as well as the server where I have deployed this. The one I have in server was bought from goDaddy but localhost had a self signed certificate.
However, every browser threw an error saying connection is not trusted, do you want to continue. After I click continue, it worked fine.
If anyone has ever bypassed this error with self signed certificate, please enlighten.
Mkcert from #FiloSottile makes this process infinitely simpler:
Install mkcert, there are instructions for macOS/Windows/Linux
mkcert -install to create a local CA
mkcert localhost 127.0.0.1 ::1 to create a trusted cert for localhost in the current directory
You're using node (which doesn't use the system root store), so you need to specify the CA explicitly in an environment variable, e.g: export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"
Finally run your express server using the setup described in various other answers (e.g. below)
boom. localhost's swimming in green.
Basic node setup:
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
const server = https.createServer({
key: fs.readFileSync('/XXX/localhost+2-key.pem'), // where's me key?
cert: fs.readFileSync('/XXX/localhost+2.pem'), // where's me cert?
requestCert: false,
rejectUnauthorized: false,
}, app).listen(10443); // get creative
How to generate an SSL certificate for localhost: link
openssl genrsa -des3 -out server.key 1024
you need to enter a password here which you need to retype in the
following steps
openssl req -new -key server.key -out server.csr
when asked "Common Name" type in: localhost
openssl x509 -req -days 1024 -in server.csr -signkey server.key -out server.crt
Some of the answers posted have pieces that were very useful to me to overcome this problem too. However, I was also interested in the minimum number of steps and, ideally, avoiding OpenSSL (on Windows 10).
So, one critical piece from the answers (credit: #TroyWorks) is that you need to edit your HOSTS file to create a fictitious server, and map that to 127.0.0.1. This assumes you are going to be doing local development.
In my case, I was using the SS certificate to secure a websocket in NodeJS, and that socket was being connected to programmatically (as opposed to via browser). So for me, it was critical that the certificate be accepted without warnings or errors, and the critical piece there was to get the cert created with a proper CN (and of course accept the cert into Trusted Authorities, as described elsewhere in the answers). Using IIS to create a self-signed cert won't create the proper CN, so I discovered the following simple command using Powershell:
New-SelfSignedCertificate -DnsName "gandalf.dummy.dev" -FriendlyName "gandalf" -CertStoreLocation "cert:\LocalMachine\My"
This has to be run in the PS Admin console, but it simply works, and puts the cert into the "Personal" section of the LocalMachine certificate store.
You can verify it got created by executing:
ls cert:\LocalMachine\My
To trust it, simply copy this and paste into "Trusted Root Certification Authorities" using Certificate Manager (making sure you are looking at the Local Machine certificates, not Current User!).
If you bind to this certificate in IIS, you should be able to hit https://gandalf.dummy.dev/ and get a secure connection without any warnings.
The final piece, using this in NodeJS, is described above and in other SO answers, so I'll only add that on Windows, it is easier to work with a pfx file that combines the cert and private key. You can export a pfx easily from the Certificate Manager, but it does affect how you use it in NodeJS. When instantiating a Server using the 'https' module, the options you would use (instead of 'key' and 'cert') would be 'pfx' and 'passphrase', as in:
var https = require('https');
var options = {
pfx: fs.readFileSync('mypfxfile'),
passphrase: 'foo'
};
var server = https.createServer(options);
Here's what's working for me
on windows
1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)
Windows Vista and Windows 7
Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.
Click Start -> All Programs -> Accessories
Right click Notepad and select Run as administrator
Click Continue on the "Windows needs your permission" UAC window.
When Notepad opens Click File -> Open
In the filename field type C:\Windows\System32\Drivers\etc\hosts
Click Open
Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net
Save
Close and restart browsers
On Mac or Linux:
Open /etc/hosts with su permission
Add 127.0.0.1 localdev.YOURSITE.net
Save it
When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.
Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.
2) create the certificate using that localdev.url
TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.
3) import the certificate as outlined on
http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/
For windows, follow these simple steps.
Open Windows PowerShell, run as administrator
install Chocolatey following this hyperlink.
use choco install mkcert to install mkcert.
run mkcert -install will create local CA.
run mkcert localhost 127.0.0.1 ::1 will create a trusted cert for localhost in the current directory.
Use the generated ./localhost+2.pem and ./localhost+2-key.pem in your server as cert and key respectively. (adding key and cert varies from server to server.)
Finally run your server using the setup described in various other answers (For Express server, it is given below)
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/', function(req, res){
res.send("HELLO!");
});
const server = https.createServer({
key: fs.readFileSync('./localhost+2-key.pem'), // path to localhost+2-key.pem
cert: fs.readFileSync('./localhost+2.pem'), // path to localhost+2.pem
requestCert: false,
rejectUnauthorized: false,
}, app).listen(3000, function(){
console.log("Successfully started server on port 3000");
});
then run your server using
node server.js
On your browser use https://localhost:3000 and you will see a lock in address bar.
Enjoy!!
If you're on OSX/Chrome you can add the self-signed SSL certificate to your system keychain as explained here: http://www.robpeck.com/2010/10/google-chrome-mac-os-x-and-self-signed-ssl-certificates
It's a manual process, but I got it working finally. Just make sure the Common Name (CN) is set to "localhost" (without the port) and after the certificate is added make sure all the Trust options on the certificate are set to "Always Trust". Also make sure you add it to the "System" keychain and not the "login" keychain.
Go to: chrome://flags/
Enable: Allow invalid certificates for resources loaded from localhost.
You don't have the green security, but you are always allowed for https://localhost in chrome.
If you're using node, why not generate them with node? This module seems to be pretty full featured:
https://github.com/andris9/pem
Note that I wouldn't generate on the fly. Generate with some kind of build script so you have a consistent certificate and key. Otherwise you'll have to authorize the newly generated self-signed certificate every time.
on windows I made the iis development certificate trusted by using MMC (start > run > mmc), then add the certificate snapin, choosing "local computer" and accepting the defaults. Once that certificate snapip is added expand the local computer certificate tree to look under Personal, select the localhost certificate, right click > all task > export. accept all defaults in the exporting wizard.
Once that file is saved, expand trusted certificates and begin to import the cert you just exported. https://localhost is now trusted in chrome having no security warnings.
I used this guide resolution #2 from the MSDN blog, the op also shared a link in his question about that also should using MMC but this worked for me.
resolution #2
There are more aspects to this.
You can achieve TLS (some keep saying SSL) with a certificate, self-signed or not.
To have a green bar for a self-signed certificate, you also need to become the Certificate Authority (CA). This aspect is missing in most resources I found on my journey to achieve the green bar in my local development setup. Becoming a CA is as easy as creating a certificate.
This resource covers the creation of both the CA certificate and a Server certificate and resulted my setup in showing a green bar on localhost Chrome, Firefox and Edge:
https://ram.k0a1a.net/self-signed_https_cert_after_chrome_58
Please note: in Chrome you need to add the CA Certificate to your trusted authorities.
SMH, a lot of hours wasted on this due to lack of proper documentation and not everyone uses IIS... If anyone else is still stuck on this issue I hope this helps.
Solution: Trusted Self Signed SSL CERT for localhost on Windows 10
Note: If you only need the SSL cert follow the Certification Creation section
Stack: Azure Function App(Node.js), React.js - Windows 10
Certification Creation
Step 1 - Create Certificate: OpenPowershell and run the following:
New-SelfSignedCertificate -NotBefore (Get-Date) -NotAfter (Get-Date).AddYears(5) `
-Subject "CN=localhost" -KeyAlgorithm "RSA" -KeyLength 2048 `
-HashAlgorithm "SHA256" -CertStoreLocation "Cert:\CurrentUser\My" `
-FriendlyName "HTTPS Development Certificate" `
-TextExtension #("2.5.29.19={text}","2.5.29.17={text}DNS=localhost")
Step 2 - Copy Certificate: Open Certificate Manager by pressing the windows key and search for "manage user certificates". Navigate to Personal -> Certificates and copy the localhost cert to Trusted Root Certification Authorities -> Certificates
Personal -> Certificates
Trusted Root Certification Authorities -> Certificates
(Friendly Name will be HTTPS Development Certificate)
Step 3. Export Certificate right click cert -> All Tasks -> Export which will launch the Certificate Export Wizard:
Certificate Export Wizard
Click next
Select Yes, export the private Key Export private key
Select the following format Personal Information Exchange - PKCS #12 and leave the first and last checkboxes selected. Export format
Select a password; enter something simple if you like ex. "1111" Enter password
Save file to a location you will remember ex. Desktop or Sites (you can name the file development.pfx) Save file
Step 4. Restart Chrome
Azure Function App (Server) - SSL Locally with .PFX
In this case we will run an Azure Function App with the SSL cert.
copy the exported development.pfx file to your azure functions project root
from cmd.exe run the following to start your functions app func start --useHttps --cert development.pfx --password 1111" (If you used a different password and filename don't forget to update the values in this script)
Update your package.json scripts to start your functions app:
React App (Client) - Run with local SSL
Install openssl locally, this will be used to convert the development.pfx to a cert.pem and server.key. Source - Convert pfx to pem file
open your react app project root and create a cert folder. (project-root/cert)
create a copy of the development.pfx file in the cert folder. (project-root /cert/development.pfx)
open command prompt from the cert directory and run the following:
convert development.pfx to cert.pem: openssl pkcs12 -in development.pfx -out cert.pem -nodes
extract private key from development.pfx to key.pem: openssl pkcs12 -in development.pfx -nocerts -out key.pem
remove password from the extracted private key: openssl rsa -in key.pem -out server.key
update your .env.development.local file by adding the following lines:
SSL_CRT_FILE=cert.pem
SSL_KEY_FILE=server.key
start your react app npm start
If you need to go a step further than #alon's detailed steps and also create a self signed ca:
https.createServer({
key: fs.readFileSync(NODE_SSL_KEY),
cert: fs.readFileSync(NODE_SSL_CERT),
ca: fs.readFileSync(NODE_SSL_CA),
}, app).listen(PORT, () => {});
package.json
"setup:https": "openssl genrsa -out src/server/ssl/localhost.key 2048
&& openssl req -new -x509 -key src/server/ssl/localhost.key -out src/server/ssl/localhost.crt -config src/server/ssl/localhost.cnf
&& openssl req -new -out src/server/ssl/localhost.csr -config src/server/ssl/localhost.cnf
&& openssl x509 -req -in src/server/ssl/localhost.csr -CA src/server/ssl/localhost.crt -CAkey src/server/ssl/localhost.key -CAcreateserial -out src/server/ssl/ca.crt",
Using the localhost.cnf as described:
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = UK
ST = State
L = Location
O = Organization Name
OU = Organizational Unit
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = #alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost
in my case the .cert always change to default ( thats mean denied ) what ever we have change to always trusted.
my device is macOS.
command + space , type keychain access and open it.
so we need to drag and drop into System Keychains -> System for the .cert file and double click on file -> get info -> make it change always trusted
so my chrome for localhost or 127.0.0.1 the hyperlink proccess unsafe are visible , before its gone type.
openssl genrsa -out server.key 2048
openssl req -new -x509 -key server.key -out server.cert -days 365
To follow up on answers from #Alon and #Diego above, the following should eliminate some of the manual browsers steps:
Create your request config file [as ./req.cnf]:
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = NG
ST = Lagos
L = Ikeja
O = Acme
OU = Dev
CN = localhost
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = #alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost
Create your certificate files [by running the following in your terminal]:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout client-cert.key -out client-cert.pem -config req.cnf -sha256
Add as trusted certificates to your Keychain:
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ./client-cert.pem
Note: Update the req.cnf according to your specific location, etc.
Note: This procedure was tested on MacOS High Sierra (10.13.6). If you're on Windows, you may need an alternative command for Step 3.

How to create .pem files for https web server

I'm using the Express framework in Node.js to create a web server. I want to use ssl for the web server's connection.
The code to create the https web server is as below.
var app = express.createServer({
key: fs.readFileSync('./conf/key.pem'),
cert: fs.readFileSync('./conf/cert.pem')
});
module.exports = app;
Question: How to create the key.pem and cert.pem required by express?
The two files you need are a PEM encoded SSL certificate and private key. PEM encoded certs and keys are Base64 encoded text with start/end delimiters that look like -----BEGIN RSA PRIVATE KEY----- or similar.
To create an SSL certificate you first need to generate a private key and a certificate signing request, or CSR (which also contains your public key).You can do this in a variety of ways, but here's how in OpenSSL.
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
This will cause you to enter an interactive prompt to generate a 2048-bit RSA private key and a CSR that has all the information you choose to enter at the prompts. (Common Name is a legacy location where domain names used to go, but modern browsers require an extension called SubjectAlternativeName now. However, when submitting to a CA they will put CN values in SAN) Once you've done this you would normally submit this CSR to a trusted certificate authority and once they've validated your request you would receive a certificate.
If you don't care about your certificate being trusted (usually the case for development purposes) you can just create a self-signed certificate. To do this, we can use almost the same line, but we'll pass some extra parameters. The interactive prompt doesn't support Subject Alternative Name (SAN), which is required in most modern clients, so we pass it on the CLI via the -addext flag. You'll need to change mydnsname.com to the right name for your uses. Be sure to keep DNS: though!
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem -addext "subjectAltName = DNS:mydnsname.com"
This will give you a cert (valid for 10 years) and key pair that you can use in the code snippet you posted.
Just follow this procedure :
create the folder where you want to store your key & certificate :
mkdir conf
go to that directory :
cd conf
grab this ca.cnf file to use as a configuration shortcut :
wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/ca.cnf
create a new certificate authority using this configuration :
openssl req -new -x509 -days 9999 -config ca.cnf -keyout ca-key.pem -out ca-cert.pem
now that we have our certificate authority in ca-key.pem and ca-cert.pem, let's generate a private key for the server :
openssl genrsa -out key.pem 4096
grab this server.cnf file to use as a configuration shortcut :
wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/server.cnf
generate the certificate signing request using this configuration :
openssl req -new -config server.cnf -key key.pem -out csr.pem
sign the request :
openssl x509 -req -extfile server.cnf -days 999 -passin "pass:password" -in csr.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem
I found this procedure here, along with more information on how to use these certificates.
An alternative is to generate the certificates with the pem library using the createCertificate method of the class.
The process would be as follows:
Install openssl in your system if not there already, for instance for windows 10 the a compiled version of the sources (seems like the most open one) can be found here: https://curl.se/windows/ the explanations of how it is compiled and safeguarded are here: https://wiki.openssl.org/index.php/Binaries. For the source https://www.openssl.org/community/binaries.html
For windows, you may want to add the diretory of the openssl.bin file to the system environment path variable (https://www.architectryan.com/2018/08/31/how-to-change-environment-variables-on-windows-10/) or pass the location of the file to the PEM library.
Instal pem using (documentation here: https://github.com/Dexus/pem
npm i pem
at the command line at the root of the server.
From the documentation you can see that a simple https server with the keys can be created simply by:
const https = require('https')
const pem = require('pem')
pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => {
if (err) {
throw err
}
https.createServer({ key: keys.clientKey, cert: keys.certificate }, (req, res) => {
res.end('o hai!')
}).listen(443)
})
or using express
npm i express
at the command line at the root of the server):
const https = require('https')
const pem = require('pem')
const express = require('express')
pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => {
if (err) {
throw err
}
const app = express()
app.get('/', (req, res) => {
res.send('o hai!')
})
https.createServer({ key: keys.clientKey, cert: keys.certificate }, app).listen(443)
})
Just changed the var for const as appropiate, and functions for arrow functions

Resources