想嘗試下在 Ubuntu 20.04 環境下,簡簡單單地建一個 https server.

先開一個 project folder:

mkdir https_server
cd https_server

製作 SSL 自簽章證書

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

然後會出現問答環節,因為只是測試 https,不必認真填寫,不斷按 Enter 使用預設值即可。

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 例子:

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 例子:

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 輸入以下 command 查看:

curl -k <https://localhost:8443>

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

提示:以上純粹作為測試使用,請勿用於 Production environment (生產環境)。

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

Recommended Posts

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments