Nodejs建立HTTPS伺服器

來源:互聯網
上載者:User

標籤:leave   簡單   about   php   getting   cat   arch   tls   targe   

Nodejs建立HTTPS伺服器

從零開始nodejs系列文章,將介紹如何利Javascript做為服務端指令碼,通過Nodejs架構web開發。Nodejs架構是基於V8的引擎,是目前速度最快的Javascript引擎。chrome瀏覽器就基於V8,同時開啟20-30個網頁都很流暢。Nodejs標準的web開發架構Express,可以協助我們迅速建立web網站,比起PHP的開發效率更高,而且學習曲線更低。非常適合小型網站,個人化網站,我們自己的Geek網站!!

關於作者

  • 張丹(Conan), 程式員Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: [email protected]

轉載請註明出處:
http://blog.fens.me/nodejs-https-server/

前言

互連網應用越來越多,網路安全問題應該值得大家注意起來,特別是對於有線上支付業務的網站!為保證使用者的賬戶安全,應該使用HTTPS協議代替HTTP協議,在資料轉送層保持加密。

大部分的美國網站,當涉及到個人資訊時,如果不提供HTTPS的服務,多數使用者都會拒絕使用的。中國的網民什麼時候,才會有這種意識呢?

目錄

  1. HTTP和HTTPS介紹
  2. 用Nodejs建立HTTPS伺服器(Win7)
  3. 用Nodejs建立HTTPS伺服器(Linux)
  4. 抓取請求,驗證加密
1. HTTP和HTTPS介紹

HTTP: 超文字傳輸通訊協定 (HTTP) (HTTP-Hypertext transfer protocol) 是一種詳細規定了瀏覽器和全球資訊網伺服器之間互相通訊的規則,通過網際網路傳送全球資訊網文檔的資料傳送協議。

HTTPS:(全稱:Hypertext Transfer Protocol over Secure Socket Layer),是以安全為目標的HTTP通道,簡單講是HTTP的安全版。即HTTP下加入SSL層,HTTPS的安全基礎是SSL,因此加密的詳細內容就需要SSL。 它是一個URI scheme(抽象標識符體系),句法類同http:體系。用於安全的HTTP資料轉送。https:URL表明它使用了HTTP,但HTTPS存在不同於HTTP的預設連接埠及一個加密/身分識別驗證層(在HTTP與TCP之間)。這個系統的最初研發由網景公司進行,提供了身分識別驗證與加密通訊方法,現在它被廣泛用於全球資訊網上安全敏感的通訊,例如交易支付方面。

HTTPS和HTTP的區別

  • https協議需要到ca申請認證,一般免費認證很少,需要交費。
  • http是超文字傳輸通訊協定 (HTTP),資訊是明文傳輸,https 則是具有安全性的ssl加密傳輸協議。
  • http和https使用的是完全不同的串連方式,用的連接埠也不一樣,前者是80,後者是443。
  • http的串連很簡單,是無狀態的;HTTPS協議是由SSL+HTTP協議構建的可進行加密傳輸、身份認證的網路通訊協定,比http協議安全。

HTTP和HTTPS的介紹,摘自http://baike.baidu.com/view/14121.htm

在Nodejs中,我們可以通過內建的https庫,來實現HTTPS伺服器。

Nodejs的HTTPS使用文檔:http://nodejs.org/api/https.html

2. 用Nodejs建立HTTPS伺服器(Win7)

系統內容

  • win7 64bit
  • IP: 192.168.1.13
  • Nodejs:v0.10.5
  • Npm:1.2.19

建立express的開發環境

~ D:\workspace\javascript>express -e  nodejs-https~ D:\workspace\javascript>cd nodejs-https && npm install[email protected] node_modules\ejs[email protected] node_modules\express├── [email protected]├── [email protected]├── [email protected]├── [email protected]├── [email protected]├── [email protected]├── [email protected]├── [email protected]├── [email protected]├── [email protected] ([email protected])└── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected])

我本地已經安裝了git用戶端msysgit,其中包括了openssl程式。

~ D:\workspace\javascript\nodejs-https>git --versiongit version 1.8.1.msysgit.1~ D:\workspace\javascript\nodejs-https>openssl version -aOpenSSL 0.9.8e 23 Feb 2007built on: Sat Sep 15 20:34:58 EDT 2007platform: MSysoptions:  bn(64,32) md2(int) rc4(idx,int) des(ptr,risc1,16,long) blowfish(idx)compiler: gcc -D_WINDLL -DOPENSSL_PIC -DOPENSSL_THREADS  -DDSO_DLFCN -DHAVE_DLFCN_H -DTERMIOS -DL_ENDIAN -D__CYGWIN__ -fomit-frame-pointer -fnative-struct -O3 -mcpu=pentium -march=i486 -Wall -DOPENSSL_BN_ASM_PART_WORDS -DOPENSSL_IA32_SSE2 -DSHA1_ASM -DMD5_ASM -DRMD160_ASM -DAES_ASMOPENSSLDIR: "/usr/ssl"

openssl產生認證檔案

#產生私密金鑰key檔案:~ D:\workspace\javascript\nodejs-https>openssl genrsa -out privatekey.pem 1024Generating RSA private key, 1024 bit long modulus...........................++++++........++++++e is 65537 (0x10001)#通過私密金鑰產生CSR認證簽名~ D:\workspace\javascript\nodejs-https>openssl req -new -key privatekey.pem -out certrequest.csrYou are about to be asked to enter information that will be incorporatedinto your certificate request.What you are about to enter is what is called a Distinguished Name or a DN.There are quite a few fields but you can leave some blankFor some fields there will be a default value,If you enter ‘.‘, the field will be left blank.-----Country Name (2 letter code) [AU]:CNState or Province Name (full name) [Some-State]:BeijingLocality Name (eg, city) []:BeijingOrganization Name (eg, company) [Internet Widgits Pty Ltd]:fens.meOrganizational Unit Name (eg, section) []:fens.meCommon Name (eg, YOUR name) []:Conan ZhangEmail Address []:[email protected]Please enter the following ‘extra‘ attributesto be sent with your certificate requestA challenge password []:An optional company name []:# 通過私密金鑰和認證簽名產生認證檔案~ D:\workspace\javascript\nodejs-https>openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pemSignature oksubject=/C=CN/ST=Beijing/L=Beijing/O=fens.me/OU=fens.me/CN=Conan Zhang/[email protected]Getting Private key

新產生了3個檔案:certificate.pem, certrequest.csr, privatekey.pem

~ D:\workspace\javascript\nodejs-https>ls -ltotal 17-rwx------  1 4294967295 mkpasswd 877 Dec 14 10:53 app.js-rwx------  1 4294967295 mkpasswd 956 Dec 14 11:22 certificate.pem-rwx------  1 4294967295 mkpasswd 704 Dec 14 11:21 certrequest.csrdrwx------+ 1 4294967295 mkpasswd   0 Dec 14 11:10 node_modules-rwx------  1 4294967295 mkpasswd 216 Dec 14 11:03 package.json-rwx------  1 4294967295 mkpasswd 887 Dec 14 11:20 privatekey.pemdrwx------+ 1 4294967295 mkpasswd   0 Dec 14 10:53 publicdrwx------+ 1 4294967295 mkpasswd   0 Dec 14 10:53 routesdrwx------+ 1 4294967295 mkpasswd   0 Dec 14 10:53 views
  • privatekey.pem: 私密金鑰
  • certrequest.csr: CSR認證簽名
  • certificate.pem: 認證檔案

修改開機檔案:app.js

~ vi app.js//最下面var https = require(‘https‘)    ,fs = require("fs");var options = {    key: fs.readFileSync(‘./privatekey.pem‘),    cert: fs.readFileSync(‘./certificate.pem‘)};https.createServer(options, app).listen(3011, function () {    console.log(‘Https server listening on port ‘ + 3011);});

啟動伺服器:

~ D:\workspace\javascript\nodejs-https>node app.jsExpress server listening on port 3000Https server listening on port 3011

開啟瀏覽器:HTTP訪問

HTTPS訪問

查看認證

由於我們認證是自己建立的,沒有經過第三方機構的驗證,因此會出現警告的提示。大家可以去有資質的網路電訊廠商,去申請自己的認證。比如:godaddy SSL Certificates,優惠碼:WOWfensme

這樣我們就在win7完整的HTTPS伺服器建立。

3. 用Nodejs建立HTTPS伺服器(Linux)

建立過程與win7類似

系統內容

  • Linux: Ubuntu 12.04.2 LTS 64bit deskop
  • IP: 192.168.1.20
  • Nodejs: npm 1.2.21
  • node v0.11.2

建立express項目

~ cd /home/conan/nodejs~ express -e  nodejs-https~ cd nodejs-https~ sudo npm install

用openssl產生認證檔案

~ openssl version -aOpenSSL 1.0.1 14 Mar 2012built on: Tue Jun  4 07:26:06 UTC 2013platform: debian-amd64options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)compiler: cc -fPIC -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DOPENSSL_NO_TLS1_2_CLIENT -DOPENSSL_MAX_TLS1_2_CIPHER_LENGTH=50 -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASMOPENSSLDIR: "/usr/lib/ssl"~ openssl genrsa -out privatekey.pem 1024~ openssl req -new -key privatekey.pem -out certrequest.csr ~ openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

修改檔案app.js

~ vi app.js//在最下面var https = require(‘https‘)    ,fs = require("fs");var options = {    key: fs.readFileSync(‘./privatekey.pem‘),    cert: fs.readFileSync(‘./certificate.pem‘)};https.createServer(options, app).listen(3011, function () {    console.log(‘Https server listening on port ‘ + 3011);});

啟動伺服器

~ node app.jsExpress server listening on port 3000Https server listening on port 3011

開啟瀏覽器:

4. 抓取請求,驗證加密

為了驗證資料在傳輸過程中是加密的,我們用wireshark抓取網路包。

HTTP請求:http://192.168.1.20:3000/users?a=111

HTTPS請求:https://192.168.1.20:3011/users?a=112

在HTTP下面,URL請求的參數是被暴露的。在HTTPS下面,URL的請求參數是被加密的。因此,希望需要填寫個人資訊,及線上支付的網站,都把HTTPS伺服器搭建起來。防止私密資料,在網路傳輸過程中被擷取。

轉載請註明出處:
http://blog.fens.me/nodejs-https-server/

 

This entry was posted in Javascript語言實踐, 網路技術

贊助商廣告(購買)
  • Pingback: Nodejs學習路線圖 | 粉絲日誌()

  • Willin Wang

    mark

  • Min

    mark!

  • wretchy

    mark

  • lenchs

    mark

  • HelloQiu

    你好,我有一個使用express建立的https,但不知道總是不明的不能訪問,進程和連接埠都正常,就是網頁打不開,以下為代碼:
    var app = express();
    app.get(‘/a’, function(req, res) {….});
    app.get(‘/b’, function(req, res) {….});
    var credentials = {
    key: fs.readFileSync(‘k.key’, ‘utf8’),
    cert: fs.readFileSync(‘c.crt’, ‘utf8’),
    passphrase: ‘****************’
    }
    https.createServer(credentials, app).listen(1234);

    • Conan Zhang

      先按文章中配置試一下吧。

  • fuchao2012

    working with the crawls in https. helps alot.

    • Conan Zhang

       , hey!

  • skytouchzyt

    為什麼我在本地建立https可以訪問,上傳到伺服器建立,就提示ssl串連錯誤?

    • Conan Zhang

      認證沒配置對吧?

  • 葉忠

    您好,我在github上下了一個SkyRTC的demo,https://github.com/LingyuCoder/SkyRTC-demo
    準備加ssl的時候怎麼都不行,我已經試了好多版本的方法了,看了不少YouTube的視頻,還是不行,請問您可以你幫幫我嗎?
    這個是demo的代碼

    var express = require(‘express’);
    var app = express();
    var server = require(‘http’).createServer(app);
    var SkyRTC = require(‘skyrtc’).listen(server);
    var path = require(“path”);
    var port = process.env.PORT || 3000;
    server.listen(port);

    下面的是我測試的

    /*

    var express = require(‘express’);

    var app = express();

    const https = require(‘https’);//.createServer(app);

    const fs = require(‘fs’);

    var path = require(“path”);

    var options = {

    key: fs.readFileSync(‘./privatekey.pem’),

    cert: fs.readFileSync(‘.server.pem’)

    };

    const server = https.createServer(options, app);

    var SkyRTC = require(‘skyrtc’).listen(server);

    var port = process.env.PORT || 80;

    server.listen(port);

    */

    /*

    var express = require(‘express’);

    var app = express();

    var path = require(“path”);

    const fs = require(‘fs’);

    var options = {

    key: fs.readFileSync(‘./privatekey.pem’),

    cert: fs.readFileSync(‘.server.pem’)

    };

    var server = require(‘https’).createServer(options, app);

    var SkyRTC = require(‘skyrtc’).listen(server);

    var port = process.env.PORT || 80;

    server.listen(port);

    */

    /*44444

    var express = require(‘express’);

    var path = require(“path”);

    const https = require(‘https’)

    ,fs = require(‘fs’);

    const options = {

    key: fs.readFileSync(‘./privatekey.pem’),

    cert: fs.readFileSync(‘.server.pem’)

    };

    const server = https.createServer(options,(req, res) => {

    res.sendfile(__dirname + ‘/index.html’);

    }).listen(80);

    var app = express();

    server.on(‘request’,app);

    server.listen(80)

    var SkyRTC = require(‘skyrtc’).listen(server);

    */

    加了ssl之後全部都是網頁打不開,沒有任何報錯。
    麻煩您抽空幫我看看,謝謝

    • Conan Zhang

      抱歉我不熟悉SkyRTC 。
      如果你這種配置有問題,你也可以嘗試在前前架個nginx處理https請求,nginx和node用http串連。

      • 葉忠

        我這邊已經解決了,不過非常感謝您能抽出時間來回複。謝謝!

        • Conan Zhang

          哈哈,太好了,解決就好。

Nodejs建立HTTPS伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.