如何在 node(.js)上建立 HTTPS How to build HTTPS connection on Node(.js)

大病初癒,大概確認研究手法後,終於又可以開始寫程式了... (茶
今天想要加點東西,想到由於現在的網路攻擊頻繁,HTTPS已變成連線的主流,於是想試試如何在 node(.js) 上建立 HTTPS連線。
根據 node 官方文件說明顯示,僅需要三個步驟:
1:  var https = require('https'),   
2:     options = {  
3:      key: fs.readFileSync('./path/keys/agent-key.pem'),  
4:      cert: fs.readFileSync('./path/keys/agent-key-cert.pem')  
5:  };  
6:  var serv = https.createServer(options, app);  
Line 1: 引用https library
Line 2: 讀取 pem certificate 跟 key
Line 3: 加入 createServer 參數

實際在實作過程中發生了些問題,這裏記錄一下。

問題一:無法連上HTTPS。
一開始利用
 curl -k https://localhost:7878/  
 curl: (35) Server aborted the SSL handshake  
發生了 "server aborted the SSL handshake" 發現產生的 cert.pem 是空的,於是發生此錯誤。
PS. server 端則是出現 exception:Missing PFX or certificate + private key

問題二:如何產生pem
參考 StackOverFlow: create HTTPS server with Node.js,如下的 Line 1 跟 Line 3.
1:  openssl genrsa 1024 > key.pem  
2:  WARNING: can't open config file: /opt/anaconda1anaconda2anaconda3/ssl/openssl.cnf  
3:  openssl req -x509 -new -key key.pem > key-cert.pem  
4:  WARNING: can't open config file: /opt/anaconda1anaconda2anaconda3/ssl/openssl.cnf  
5:  Unable to load config info from /opt/anaconda1anaconda2anaconda3/ssl/openssl.cnf  

問題三:openssl 發生錯誤,找不到路徑
同問題二,出現了 openssl 找不到 folder 的問題。generate RSA 的時候還只是 warning,建立 certificate 就發生了錯誤(其實這是一個已知的anaconda-issue-137 )。解法很簡單,直接更新 anaconda 的 openssl package即可。
PS1. 如何確認 openssl 的安裝路徑
 > openssl version -d
PS2. 如何確認 anaconda 安裝路徑
> conda info

問題四:如何讓http & https 聽同一個 port
根據 StackOverFlow : node.js http and https over the same port 的說明,一般是走不同的port。


其他(有空再了解)
a. 什麼是pem
b. codeformater 所 gen出來的 html code 總是無法正確顯示 ">" 而出現 "&qt;".
c. 目前的 SSL certificate 只有一份,如何產生多份?如何管理?

Comments

Popular posts from this blog

股票評價(Stock Valuation) - 股利折現模型

openwrt feed的使用

How to convert Markdown into HTML