#!/usr/bin/env python # -*- coding: utf-8 -*- """ SSL-Zertifikat-Generator für die MYP-Plattform Erstellt selbstsignierte SSL-Zertifikate für die lokale Entwicklung """ import os import datetime import sys # Überprüfen, ob die notwendigen Pakete installiert sind try: from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption except ImportError: print("Fehler: Paket 'cryptography' nicht gefunden.") print("Bitte installieren Sie es mit: pip install cryptography") sys.exit(1) def create_self_signed_cert(cert_path, key_path, hostname="localhost"): """ Erstellt ein selbstsigniertes SSL-Zertifikat mit dem angegebenen Hostnamen. Args: cert_path: Pfad zur Zertifikatsdatei key_path: Pfad zur privaten Schlüsseldatei hostname: Hostname für das Zertifikat (Standard: localhost) """ # Verzeichnis erstellen, falls es nicht existiert cert_dir = os.path.dirname(cert_path) if cert_dir and not os.path.exists(cert_dir): os.makedirs(cert_dir, exist_ok=True) # Privaten Schlüssel generieren private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, ) # Schlüsseldatei schreiben with open(key_path, "wb") as key_file: key_file.write(private_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption() )) # Name für das Zertifikat erstellen subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, hostname), ]) # Zertifikat erstellen cert = x509.CertificateBuilder().subject_name( subject ).issuer_name( issuer ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName([x509.DNSName(hostname)]), critical=False, ).sign(private_key, hashes.SHA256()) # Zertifikatsdatei schreiben with open(cert_path, "wb") as cert_file: cert_file.write(cert.public_bytes(Encoding.PEM)) print(f"Selbstsigniertes SSL-Zertifikat für '{hostname}' erstellt:") print(f"Zertifikat: {cert_path}") print(f"Schlüssel: {key_path}") print(f"Gültig für 1 Jahr.") if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Erstellt selbstsignierte SSL-Zertifikate für die lokale Entwicklung") parser.add_argument("-c", "--cert", default="/home/user/Projektarbeit-MYP/backend/app/certs/myp.crt", help="Pfad zur Zertifikatsdatei") parser.add_argument("-k", "--key", default="/home/user/Projektarbeit-MYP/backend/app/certs/myp.key", help="Pfad zur Schlüsseldatei") parser.add_argument("-n", "--hostname", default="localhost", help="Hostname für das Zertifikat") args = parser.parse_args() create_self_signed_cert(args.cert, args.key, args.hostname)