build a https server for localhost

we need a local https server when https is required in product environment

let us do it now 🔨

0. install openssl firstly!

1.prepare a CA request files

1.1 generate a RSA server key

1
openssl genrsa -out server.key 2048

1.2 generate a CA request file

1
2
openssl req -new -out server.req -key server.key -subj
"/C=US/ST=LosAngeles/L=LA/O=Namido/CN=127.0.0.1"

ps. '-subj' can be ignored and you can type them all in the command tool

now notice there are two files(server.key, server.req) in current directory, the .key is server private key and the .req is CA request file.

let us get CA signature with server.req if there is no error occured

2.make an our own CA

2.1 generate a RSA key

1
openssl genrsa -out ca.key 2048

2.2 root signature for self

1
2
openssl req -new -x509 -days 1000 -key ca.key -out ca.crt -sha256 -subj 
"/C=US/ST=LosAngeles/L=LA/O=Namido/CN=Namido CA"

notice: value of CN in -subj is the name of CA

2.3 generate a server certificate with this root signature

1
2
openssl x509 -req -in server.req -out server.crt -CAkey ca.key -CA ca.crt -days 1000 
-sha256 -CAcreateserial -CAserial server.serial

the server.crt file that via our own CA generated will exists in current directory if no error occur.

3.0 finally process

3.1 add them to server configuration

copy ca.crt, server.crt, server.key three files to HTTPS server such as Nginx/Apache or other server by using server.crt as server certificate, server.key as server private key, ca.crt as keychain certificate.

for example:

this is a node.js server souce code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var express = require('express');

var app = express();

var https = require('https');

var fs = require('fs');

var options = {

key: fs.readFileSync('./keys/server.key'),

ca: [fs.readFileSync('./keys/ca.crt')],

cert: fs.readFileSync('./keys/server.crt')

};

https.createServer(options, app).listen(3000, function(req, res) {

console.log('server is running on port 3000');

});

3.2 make it valid

copy ca.crt to your local computer somewhere and double click it and modify always trust in your keychain to make it valid.

done! 🎉