前面說了一些基礎概念,本篇文章就實際來動手做做看用 OpenSSL 、 Nginx 加上 GO 開發一個簡單的 TLS 範例。
建立 CA key
由於我們要自己簽 SSL 所以需要透過 OpenSSL 先建立一個 CA 的私鑰。
1
2
3
4
5
6
7
8
openssl genrsa -out ca.key 2048Generating RSA private key, 2048 bit long modulus (2 primes)........+++++
......+++++
e is 65537(0x010001)root@internalTest:/home/ca# ls
ca.key
建立 CA CRT
建立完 CA 的私鑰後,我們還需要建立 CA 的身分證 CA CRT ,這個身分證就代表 CA 公開出去的所有人都看得到。
建立 server 的私鑰 , 用來給 nginx server 的 TLS private key。
1
2
3
4
5
6
openssl genrsa -out server.key 2048Generating RSA private key, 2048 bit long modulus (2 primes)...................+++++
.............................................................................................+++++
e is 65537(0x010001)
cat /etc/hosts
### Host Database## localhost is used to configure the loopback interface# when the system is booting. Do not change this entry.##52.163.243.191 example.com
...
修改完成後測試一下能不能透過 https 連線到 nginx 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
curl -k https://example.com
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif;}</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully i
...
可以順利連線到,那接著可以撰寫一個簡單的 Client 去打打看 Server 囉!
Sample Client
這邊會以一個單向 TLS 認證作為示範,單向 TLS 認證大致上的動作是, Client 向 Server 發起請求。這時候 Client 會拿到 Server 的 證書( crt ) ,Client 會拿著這組 Server crt 跟 CA 的 crt 進行驗證 ,看 Server 是不是被 CA 授權的還是假冒的。
如果是假冒的那麼 Client 會拒絕連線,反之 Server 若是被 CA 認證的那 Client 就會繼續往 Server 發請求。