本文最后更新于 2025年4月22日 下午
要求:在一台连接到网络的主机上搭建https服务器,假设该主机的ip地址为:10.98.69.174。
1 创建证书
创建证书example.crt和私钥example.key,命令如下:
1
| openssl req -newkey rsa:2048 -nodes -keyout example.key -x509 -days 365 -out example.crt
|
使用命令可以查看证书详情
1
| openssl x509 -in example.crt -text -noout
|
2 创建服务器脚本
使用python编辑脚本文件https_server.py,如下:
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 27 28 29 30 31 32
| import json import ssl from http.server import HTTPServer, BaseHTTPRequestHandler
class MyRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(bytes(json.dumps({"data": "hello"}), 'utf-8'))
if __name__ == '__main__': context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) context.load_cert_chain(certfile='./example.crt', keyfile="./example.key")
ciphers = "" ciphers += "ECDHE-ECDSA-AES128-GCM-SHA256:" ciphers += "ECDHE-ECDSA-CHACHA20-POLY1305:" ciphers += "ECDHE-RSA-CHACHA20-POLY1305:" ciphers += "ECDHE-RSA-AES128-GCM-SHA256:" context.set_ciphers(ciphers)
ciphers_suit = context.get_ciphers() for i in range(len(ciphers_suit)): print(f"{i}: {ciphers_suit[i]['name']}")
httpd = HTTPServer(('0.0.0.0', 4443), MyRequestHandler) httpd.socket = context.wrap_socket(httpd.socket, server_side=True) httpd.serve_forever()
|
修改上述代码中的ciphers可以调整服务器支持的加密类型。
3 运行服务器
通过以下命令执行脚本,运行服务器
4 访问服务器
可以在局域网内通过火狐浏览器访问以下网址,查看https服务器是否已经生效
1
| https://10.98.69.174:4443
|