TLS 套接字伺服器和客戶端
此常規 TCP 連線與常規 TCP 連線之間的唯一主要區別是私鑰和公共證書,你必須將其設定為選項物件。
如何建立金鑰和證書
此安全過程的第一步是建立私鑰。什麼是私鑰?基本上,它是一組用於加密資訊的隨機噪聲。從理論上講,你可以建立一個金鑰,並使用它來加密你想要的任何金鑰。但最佳做法是為特定事物設定不同的金鑰。因為如果有人偷了你的私鑰,那就像是有人偷了你的房門鍵。想象一下,如果你使用相同的鍵來鎖定你的車,車庫,辦公室等。
openssl genrsa -out private-key.pem 1024
一旦我們擁有了私鑰,我們就可以建立一個 CSR(證書籤名請求),這是我們要求由一個花哨的權威機構簽署私鑰的請求。這就是你必須輸入與貴公司相關的資訊的原因。簽名機構將檢視此資訊,並用於驗證你。在我們的例子中,你鍵入的內容並不重要,因為在下一步我們將自己簽署我們的證書。
openssl req -new -key private-key.pem -out csr.pem
現在我們已經完成了我們的論文工作,現在是時候假裝我們是一個很酷的簽名機構。
openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem
現在你擁有了私鑰和公共證書,你可以在兩個 NodeJS 應用程式之間建立安全連線。而且,正如你在示例程式碼中看到的那樣,這是一個非常簡單的過程。
重要!
自從我們自己建立公共證書以來,我們的證書毫無價值,因為我們是無名小卒。預設情況下,NodeJS 伺服器不會信任這樣的證書,這就是為什麼我們需要告訴它實際信任我們的證書,並使用以下選項 rejectUnauthorized:false。非常重要 :永遠不要在生產環境中將此變數設定為 true。
TLS 套接字伺服器
'use strict';
var tls = require('tls');
var fs = require('fs');
const PORT = 1337;
const HOST = '127.0.0.1'
var options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('public-cert.pem')
};
var server = tls.createServer(options, function(socket) {
// Send a friendly message
socket.write("I am the server sending you a message.");
// Print the data that we received
socket.on('data', function(data) {
console.log('Received: %s [it is %d bytes long]',
data.toString().replace(/(\n)/gm,""),
data.length);
});
// Let us know when the transmission is over
socket.on('end', function() {
console.log('EOT (End Of Transmission)');
});
});
// Start listening on a specific port and address
server.listen(PORT, HOST, function() {
console.log("I'm listening at %s, on port %s", HOST, PORT);
});
// When an error occurs, show it.
server.on('error', function(error) {
console.error(error);
// Close the connection after the error occurred.
server.destroy();
});
TLS 套接字客戶端
'use strict';
var tls = require('tls');
var fs = require('fs');
const PORT = 1337;
const HOST = '127.0.0.1'
// Pass the certs to the server and let it know to process even unauthorized certs.
var options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('public-cert.pem'),
rejectUnauthorized: false
};
var client = tls.connect(PORT, HOST, options, function() {
// Check if the authorization worked
if (client.authorized) {
console.log("Connection authorized by a Certificate Authority.");
} else {
console.log("Connection not authorized: " + client.authorizationError)
}
// Send a friendly message
client.write("I am the client sending you a message.");
});
client.on("data", function(data) {
console.log('Received: %s [it is %d bytes long]',
data.toString().replace(/(\n)/gm,""),
data.length);
// Close the connection after receiving the message
client.end();
});
client.on('close', function() {
console.log("Connection closed");
});
// When an error ocoures, show it.
client.on('error', function(error) {
console.error(error);
// Close the connection after the error occurred.
client.destroy();
});