Nodejs使用TLS
1. 使用openssl生成服务器和客户端证书
生成服务器证书,服务器使用自签名证书(也就是自己扮演CA)
1 2 3 | openssl genrsa - out server-key.pem 2048 openssl req - new -sha256 -key server-key.pem - out server-csr.pem //在CN处填写服务器主机名www.qikangwei.com openssl x509 -req - in server-csr.pem -signkey server-key.pem - out server-cert.pem |
将服务器私钥server-key.pem和CA根证书server-cert.pem复制到客户端,然后生成客户端证书
1 2 3 | openssl genrsa - out client-key.pem 2048 openssl req - new -sha256 -key client-key.pem - out client-csr.pem //在CN出填写客户端主机名 openssl x509 -req -CA server-cert.pem -CAkey server-key.pem -CAcreateserial - in client-csr.pem - out client-cert.pem |
2. 创建服务器和客户端脚本
服务器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | var tls = require( 'tls' ); var fs = require( 'fs' ); var options = { key: fs.readFileSync( 'server-key.pem' ), cert: fs.readFileSync( 'server-cert.pem' ), ca: [ fs.readFileSync( 'server-cert.pem' ) ], requestCert: true , rejectUnauthorized: true }; var server = tls.createServer(options, function(test) { console.log( 'server connected' , test.authorized ? 'authorized' : 'unauthorized' ); test.write( "welcome!\n" ); test.setEncoding( 'utf8' ); test. on ( 'data' , function(data) { console.log(data); }); test. on ( 'close' , function() { console.log( 'client has closed' ); server.close(); }); }); server.listen(2345, function() { console.log( 'server bound' ); }); |
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | var tls = require( 'tls' ); var fs = require( 'fs' ); var options = { host: 'www.qikangwei.com' , port: 2345, key: fs.readFileSync( 'client-key.pem' ), cert: fs.readFileSync( 'client-cert.pem' ), ca: [ fs.readFileSync( 'server-cert.pem' ) ], rejectUnauthorized: true }; var client = tls.connect(options, function() { console.log( 'client connected' , client.authorized ? 'authorized' : 'unauthorized' ); process.stdin.setEncoding( 'utf8' ); process.stdin. on ( 'readable' , function() { var chunk = process.stdin.read(); if (chunk !== null ) { client.write(chunk); } }); }); client.setEncoding( 'utf8' ); client. on ( 'data' , function(data) { console.log(data); }); client.write( "happy new year!" ); |
3. 测试
服务器:
node tls-server.js
客户端:
node tls-client.js
脚本启动后,在客户端输入内容,服务器端会显示同样的内容
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
2017-04-19 Ubuntu 14.04lts安装vncserver