隨手扎
嘗試localhost的HTTPS伺服器
前言
因為一些原因,在區域網路開發環境的時後,還是需要HTTPS伺服器來做一些測試(最近瀏覽器實在太嚴格了Orz,不是HTTPS有些東西就無法做…)。
爲此,我主要參考了如何在五分鐘內建立SSL憑證和SSL是什麼鬼(方便起見,我改過標題,還請自己連回去看看原文)。前者甚至在GitHub建立了腳本可直接拿來使用,不過我決定還是親自嘗試一下。
除了上述兩篇以外,其實還有找到許多不錯的文章,還自徑往下看看參考資料。不過這兩篇,前者的CA與伺服器的私鑰、憑證是正式分開的,
此次我只想要建立一個自我簽署的憑證,能在區域網路使用就好。而後一篇足夠簡單,但應付我所需要的情況還需要做些調整。
快開始吧
使用環境:
- Linux
- OpenSSL
- Node.js
- express.js
建立伺服器私鑰(同時也是CA私鑰)
openssl genrsa -des3 -out server.key 4096
這邊我改成4096。雖然是區域網路使用,我還是想要高一點安全性。
產生欲簽署憑證
這部分可以跳過
openssl req -new -key server.key -out server.csr
這部分會填入一些資訊,然後用自己的私鑰簽署過一遍。之後在把簽名過的資訊給CA簽名。 不過因爲互動是界面能填的東西,有些我不知道怎麼填才能後讓區域網路內可以比較好的使用。 所以接著會從新建立一遍,並使用類似第一篇的方式,建立一份設定檔案。
建立設定檔案 並 產生請求憑證
編輯一個檔案 server.csr.cnf
,並編輯以下內容:
[req]
default_bits = 4096
prompt = no
default_md = sha256
distinguished_name = dn
[dn]
C=US
ST=RandomState
L=RandomCity
O=RandomOrganization
OU=RandomOrganizationUnit
emailAddress=hello@example.com
CN = localhost
[v3_req]
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = *.localhost
DNS.2 = localhost
DNS.3 = 192.168.*.*
原本v3_req之後的資訊應該是分開寫,不過我先寫在一起。然後透過這份設定,來產生需要的申請檔案:
openssl req -new -key server.key -out server.csr -config server.scr.cnf
生成CA的CRT
openssl req -new -x509 -key server.key -out ca.crt -days 365 -config server.scr.cnf
存活時間改為一年。並且直接使用同一份設定檔案XD。
建立自簽署憑證
openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey server.key -CAcreateserial -out server.crt # -extfile server.scr.cnf
存活時間改為一年。
建立HTTPS伺服器來看看吧
理論上已經寫好HTTPS溝通邏輯的伺服器軟體應該都可以用。Apache應該只要去修改設定檔即可。 這次直接用Node.js安裝的express.js來測試。
處理環境
npm init
npm install express --save
編輯index.js
var path = require('path')
var fs = require('fs')
var express = require('express')
var https = require('https')
var certOptions = {
key: fs.readFileSync(path.resolve('build/cert/server.key')),
cert: fs.readFileSync(path.resolve('build/cert/server.crt'))
}
var app = express()
app.use("/",function(req,res,next){
res.send("Hello");
});
var server = https.createServer(certOptions, app).listen(443)
調整一下憑證和私鑰路徑,用npm start
執行看看(443 port需要sudo)。
瀏覽 https://localhost/ 應該就會看到警告是自簽署的憑證(就可以加入信任來使用XD)。直接通過後,就會有Hello的文字。
快速建立自簽署簽證
上面已經建立設定檔案了,其實接著只需要這麼輸入(參考):
openssl req -x509 -new -nodes -sha256 -utf8 -days 3650 -newkey rsa:2048 -keyout server.key -out server.crt -config server.scr.cnf
這會直接建立: | 檔名 | 作用 | |:———-:|:—-:| | server.key | 私鑰 | | server.crt | 憑證 |