https模块

69 阅读1分钟

服务器结构

简介

image.png

image.png

证书准备

  • 网上购买证书(一般公司用)
  • 本地产生证书(自己作为权威机构发布证书)
    • 安装openssl
      • 下载源码,自行构建
      • 下载windows安装包
      • mac下自带
      • 通过输入命令openssl测试
    • 生成CA私钥
      • openssl genrsa -des3 -out ca-pri-key.pem 1024
      • genrsa:密钥对生成算法。
      • -des3:使用对称加密算法 DES3 对私钥进一步加密。
      • -out ca-pri-key.pem:将加密后的私钥保存到当前目录的 ca-pri-key.pem 文件中。
      • 1024:私钥的字节数。
    • 生成CA私钥(证书请求)
      • penssl req -new -key ca-pri-key.pem -out ca-pub-key.pem
      • 通过私钥文件 ca-pri-key.pem 中的内容,生成对应的公钥,保存到 ca-pub-key.pem 中。
      • 运行过程中要使用之前输入的密码来实现对私钥文件的解密。
      • 其他信息

    • 生成CA证书
    • 生成服务器私钥:openssl genrsa -out server-key.pem 1024
    • 生成服务器公钥: openssl req -new -key server-key.pem -out server-Scr.pem
    • 生成服务器证书: openssl x509 -req -CA ca-cert.crt -CAkey ca-pri-key.pem -CAcreateserial -in server-Scr.pem -out server-cert.crt

https模块

https 模块是 Node.js 内置的模块,用于创建 HTTPS 服务器或发起 HTTPS 请求。它是 http 模块的扩展,基于 SSL/TLS 协议提供安全的通信。 写法

const server = https.createServer({
    key: fs.readFileSync(path.resolve(__dirname, "path/to/private-key.pem")), // 私钥
    cert: fs.readFileSync(path.resolve(__dirname, "path/to/certificate.crt")), // 证书
}, handler);