gitscope
https://dev.kronoz.win/r/marzneshin.git
app/utils/crypto.py · v0.5.4
Source
1 12b255b Dawsh 2y ago import ssl
2 12b255b Dawsh 2y ago
3 a47eb4c Dawsh 2y ago from cryptography import x509
4 a47eb4c Dawsh 2y ago from cryptography.hazmat.backends import default_backend
5 a47eb4c Dawsh 2y ago from OpenSSL import crypto
6 a47eb4c Dawsh 2y ago
7 a47eb4c Dawsh 2y ago
8 a47eb4c Dawsh 2y ago def get_cert_SANs(cert: bytes):
9 a47eb4c Dawsh 2y ago cert = x509.load_pem_x509_certificate(cert, default_backend())
10 a47eb4c Dawsh 2y ago san_list = []
11 a47eb4c Dawsh 2y ago for extension in cert.extensions:
12 a47eb4c Dawsh 2y ago if isinstance(extension.value, x509.SubjectAlternativeName):
13 a47eb4c Dawsh 2y ago san = extension.value
14 a47eb4c Dawsh 2y ago for name in san:
15 a47eb4c Dawsh 2y ago san_list.append(name.value)
16 a47eb4c Dawsh 2y ago return san_list
17 a47eb4c Dawsh 2y ago
18 a47eb4c Dawsh 2y ago
19 a47eb4c Dawsh 2y ago def generate_certificate():
20 a47eb4c Dawsh 2y ago k = crypto.PKey()
21 a47eb4c Dawsh 2y ago k.generate_key(crypto.TYPE_RSA, 4096)
22 a47eb4c Dawsh 2y ago cert = crypto.X509()
23 a47eb4c Dawsh 2y ago cert.get_subject().CN = "Gozargah"
24 a47eb4c Dawsh 2y ago cert.gmtime_adj_notBefore(0)
25 01cdf2e Dawsh 2y ago cert.gmtime_adj_notAfter(100 * 365 * 24 * 60 * 60)
26 a47eb4c Dawsh 2y ago cert.set_issuer(cert.get_subject())
27 a47eb4c Dawsh 2y ago cert.set_pubkey(k)
28 01cdf2e Dawsh 2y ago cert.sign(k, "sha512")
29 f1ab16c Dawsh 2y ago cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode(
30 f1ab16c Dawsh 2y ago "utf-8"
31 f1ab16c Dawsh 2y ago )
32 a47eb4c Dawsh 2y ago key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf-8")
33 a47eb4c Dawsh 2y ago
34 01cdf2e Dawsh 2y ago return {"cert": cert_pem, "key": key_pem}
35 12b255b Dawsh 2y ago
36 12b255b Dawsh 2y ago
37 12b255b Dawsh 2y ago def create_secure_context(
38 01cdf2e Dawsh 2y ago client_cert: str,
39 01cdf2e Dawsh 2y ago client_key: str,
40 01cdf2e Dawsh 2y ago trusted: str,
41 12b255b Dawsh 2y ago ) -> ssl.SSLContext:
42 12b255b Dawsh 2y ago ctx = ssl.create_default_context(cafile=trusted)
43 12b255b Dawsh 2y ago ctx.load_cert_chain(client_cert, client_key)
44 01cdf2e Dawsh 2y ago ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")
45 01cdf2e Dawsh 2y ago ctx.set_alpn_protocols(["h2"])
46 12b255b Dawsh 2y ago ctx.check_hostname = False
47 12b255b Dawsh 2y ago ctx.verify_mode = ssl.CERT_NONE
48 12b255b Dawsh 2y ago return ctx