將區塊鏈節點的RPC訪問協議由HTTP修改爲HTTPS

目標

目前DAPP應用對同步節點的訪問都是通過http協議進行的,爲了提高RPC接口訪問的安全性,可以考慮將HTTP協議替換爲HTTPS協議。本文的主要目的是介紹如何將RPC的訪問協議由HTTP修改爲HTTPS。

準備工作

本文測試用例以高性能區塊鏈項目HPB爲例。
1、下載代碼:代碼路徑 https://github.com/hpb-project/go-hpb

2、安裝openssl : 代碼路徑 https://github.com/openssl/openssl ,也可以到官網下載安裝包。安裝OpenSSL主要是用於證書測試。

3、編譯go-hpb,搭建hpb私鏈並測試http請求。

HTTP測試

1、啓動私鏈節點(啓動參數需要添加rpc,rpcport)

2、執行查詢塊高度的請求

執行:curl -H “Content-Type:application/json” -X POST --data ‘{“jsonrpc”:“2.0”,“method”:“hpb_blockNumber”,“id”:1}’ http://127.0.0.1:8545

返回:{“jsonrpc”:“2.0”,“id”:1,“result”:“0x21c9”}

以上執行查詢區塊高度請求,返回區塊高度爲0x21c9。請求成功

此時將上述的http替換爲https 再次進行請求是失敗的,返回curl: (35) gnutls_handshake() failed: An unexpected TLS packet was received.的錯誤提示。

修改代碼

1、由於HTTPS協議的使用涉及到證書,因此這裏使用OpenSSL生成測試證書。

​ a、生成2048位私鑰:openssl genrsa -out server.key 2048

​ b、生成公鑰:openssl rsa -in server.key -out server.key.public

​ c、生成數字證書:openssl req -new -x509 -key server.key -out server.crt -days 365

以上執行完畢,會生成3個文件:私鑰文件server.key ,公鑰文件server.key.public,經私鑰簽名的證書文件:server.crt ,證書有效期爲365天。

2、修改go-hpb節點代碼,編譯go-hpb/network/rpc/rpcmanager.go文件,將StartHTTPEndpoint函數進行修改。

修改前:

func StartHTTPEndpoint(endpoint string, apis []API, modules []string, cors []string, vhosts []string, timeouts config.HTTPTimeouts) (net.Listener, *Server, error) {
	
	......
	go NewHTTPServer(cors, vhosts, timeouts, handler).Serve(listener)
	return listener, handler, err
}

修改後

func StartHTTPEndpoint(endpoint string, apis []API, modules []string, cors []string, vhosts []string, timeouts config.HTTPTimeouts) (net.Listener, *Server, error) {
	
	......
	//go NewHTTPServer(cors, vhosts, timeouts, handler).Serve(listener)
	currentpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	certFile := currentpath + "/server.crt"
	keyFile := currentpath + "/server.key"
	go NewHTTPServer(cors, vhosts, timeouts, handler).ServeTLS(listener, certFile, keyFile) //主要是將Serve函數替換爲ServeTLS函數,同時增加證書和私鑰路徑。
	return listener, handler, err
}

3、編譯go-hpb, 然後將證書server.crt,私鑰server.key放到go-hpb/build/bin目錄下。

​ 根據上述修改代碼,要將證書,私鑰放到ghpb進程的同一個目錄下。

HTTPS測試

1、啓動私鏈節點(啓動參數需要添加rpc,rpcport)

2、執行HTTP請求查詢塊高度的請求

執行:curl -H “Content-Type:application/json” -X POST --data ‘{“jsonrpc”:“2.0”,“method”:“hpb_blockNumber”,“id”:1}’ http://127.0.0.1:8545

此時HTTP請求無任何結果返回。

3、執行HTTPS請求查詢塊高度的請求,將上述指令中http替換爲https,同時添加-k參數即可。

執行:curl -k -H “Content-Type:application/json” -X POST --data ‘{“jsonrpc”:“2.0”,“method”:“hpb_blockNumber”,“id”:1}’ https://127.0.0.1:8545

返回:{“jsonrpc”:“2.0”,“id”:1,“result”:“0x21c9”} 。執行成功

備註

上述生成的證書僅爲測試使用,如有必要,可以找具有CA資質的機構申請證書。

THE END!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章