製作 SSL 自簽章證書 (self-signed certificate)

嘗試製作 SSL 自簽章證書 (self-signed certificate)。

想嘗試下在 Ubuntu 20.04 環境下,簡簡單單地建一個 HTTPS 伺服器。

首先,我們需要創建一個專案資料夾:

1
2
mkdir https_server
cd https_server

製作 SSL 自簽章證書

1
openssl req -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -keyout selfsigned.key -out selfsigned.cert

會進入一個問答環節。由於只是在進行 HTTPS 的測試,所以直接按 Enter 使用預設值。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Generating a RSA private key
......................................................................................++++
.......++++
writing new private key to 'selfsigned.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:HK
State or Province Name (full name) [Some-State]:Hong Kong
Locality Name (eg, city) []:Hong Kong
Organization Name (eg, company) [Internet Widgits Pty Ltd]:OldestDream's Company
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:[email protected]

測試

Node.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const fs = require('fs');
const https = require('https');

const options = {
  key: fs.readFileSync('selfsigned.key'),
  cert: fs.readFileSync('selfsigned.cert'),
  passphrase: null,
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello HTTPS\\n');
}).listen(8443);

Python 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import http.server, ssl

sslctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
sslctx.load_cert_chain(certfile='selfsigned.cert', keyfile='selfsigned.key', password=None)

server_address = ('0.0.0.0', 8443)
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = sslctx.wrap_socket(httpd.socket, server_side=True)

httpd.serve_forever()

打開 https://localhost:8443 便能看到效果了。

或者在 Terminal 輸入以下命令來查看:

1
curl -k https://localhost:8443

如果你在製作 SSL 自簽章證書時,沒有加入 -nodes 的話,便需要輸入 passphrase. 在上述例子裡,可以修改 Python 3 例子裡的 password(若不輸入,則會在運行時詢問 Enter PEM pass phrase:)和 Node.js 例子裡的 passphrase。

如果你在製作 SSL 自簽章證書時,沒有加入 -nodes 的話,你便要輸入 passphrase, 在上述例子裡,可以修改 Python 3 例子裡的 password (不輸入的話會在運行時詢問 Enter PEM pass phrase: ) 和 Node.js 例子裡的 passphrase

請注意,以上的步驟僅供測試使用,不應用於生產環境。

References

https://www.digitalocean.com/community/tutorials/how-to-create-a-self-signed-ssl-certificate-for-nginx-in-ubuntu-20-04-1

https://blog.anvileight.com/posts/simple-python-http-server/

https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener

comments powered by Disqus