Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebSocket Over SSL/TLS #49

Open
abbshr opened this issue Aug 14, 2015 · 0 comments
Open

WebSocket Over SSL/TLS #49

abbshr opened this issue Aug 14, 2015 · 0 comments

Comments

@abbshr
Copy link
Owner

abbshr commented Aug 14, 2015

WebSocket over tls/ssl

WebSocket协议的安全设计里规定了基于TLS/SSL的传输. 这种加密形式和HTTPS类似, 称作WSS.

在协议实现上该如何做呢? 其实这部分不是WebSocket要承担的, TLS(传输层加密)/SSL(安全套接层)很明显是在TCP之上做的一层数据加密处理, 即OSI七层模型中的会话层, 而诸如HTTP, WebSocket, FTP等协议则属于应用层, 所以安全不安全不在WebSocket本身.

高层的应用层协议能透明的创建于TLS协议之上。TLS协议在应用层协议通信之前就已经完成加密算法、通信密钥的协商以及服务器认证工作。在此之后应用层协议所传送的数据都会被加密,从而保证通信的私密性. 这正是HTTPS的实现机制.

下图清楚地描述了安全协议的架构:

    +-------------------------------------------+
    | WebSocket |    HTTP    |   POP   |  IMAP  |
    +-------------------------------------------+
    |                   SSL                     |
    |                   TLS                     |
    +-------------------------------------------+
    |               Network Layer               |
    |                                           |
    +-------------------------------------------+

为了演示这一过程, 我们利用OpenSSL提供的加密算法可以很容易给自己的服务器颁发一个自签名证书.

签名需要RSA私钥, 先用OpenSSL生成一对RSA密钥:

# 强度2048的RSA密钥
openssl genrsa -out rsa.pem 2048

自签名证书:

 openssl req -new -x509 -days 365 -out cert.pem

借助RocketEngine实现WSS. 启动HTTPS服务器实例:

https = require 'https'
fs = require 'fs'
rocket = require 'rocket-engine'
{RocketServer} = rocket

httpServer = https.createServer 
    key: fs.readFileSync './rsa.pem'
    cert: fs.readFileSync './cert.pem'  
, (req, res) ->
    # ...

rocketServer = new RocketServer httpServer
.on 'connected', (socket) -> # ...

rocket.listen httpServer, () ->
    httpServer.listen 80

参考文章:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant