#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 使用OpenSSL命令行工具创建简单的自签名证书 不依赖Python的cryptography库 """ import os import subprocess import sys def create_ssl_dir(): """创建ssl目录""" if not os.path.exists("ssl"): os.makedirs("ssl") print("✅ 创建ssl目录") def create_certificate_with_openssl(): """使用OpenSSL命令创建证书""" print("🔑 使用OpenSSL创建自签名证书...") # 检查OpenSSL是否可用 try: subprocess.run(["openssl", "version"], check=True, capture_output=True) except (subprocess.CalledProcessError, FileNotFoundError): print("❌ OpenSSL未安装或不在PATH中") print("📝 请安装OpenSSL或使用其他方法") return False # 创建私钥 key_cmd = [ "openssl", "genrsa", "-out", "ssl/key.pem", "2048" ] # 创建证书 cert_cmd = [ "openssl", "req", "-new", "-x509", "-key", "ssl/key.pem", "-out", "ssl/cert.pem", "-days", "365", "-subj", "/C=CN/ST=Beijing/L=Beijing/O=Distance System/CN=localhost" ] try: print(" 生成私钥...") subprocess.run(key_cmd, check=True, capture_output=True) print(" 生成证书...") subprocess.run(cert_cmd, check=True, capture_output=True) print("✅ SSL证书创建成功!") print(" 🔑 私钥: ssl/key.pem") print(" 📜 证书: ssl/cert.pem") return True except subprocess.CalledProcessError as e: print(f"❌ OpenSSL命令执行失败: {e}") return False def create_certificate_manual(): """提供手动创建证书的说明""" print("📝 手动创建SSL证书说明:") print() print("方法1 - 使用在线工具:") print(" 访问: https://www.selfsignedcertificate.com/") print(" 下载证书文件并重命名为 cert.pem 和 key.pem") print() print("方法2 - 使用Git Bash (Windows):") print(" 打开Git Bash,进入项目目录,执行:") print(" openssl genrsa -out ssl/key.pem 2048") print(" openssl req -new -x509 -key ssl/key.pem -out ssl/cert.pem -days 365") print() print("方法3 - 暂时使用HTTP:") print(" 运行: python main_web.py") print(" 注意: HTTP模式下手机摄像头可能无法使用") def main(): """主函数""" create_ssl_dir() # 检查证书是否已存在 if os.path.exists("ssl/cert.pem") and os.path.exists("ssl/key.pem"): print("✅ SSL证书已存在") return print("🔍 尝试创建SSL证书...") # 尝试使用OpenSSL if create_certificate_with_openssl(): return # 提供手动创建说明 create_certificate_manual()