|
| 1 | +import tempfile |
| 2 | +from dataclasses import dataclass |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +from OpenSSL.crypto import (FILETYPE_PEM, TYPE_RSA, X509, PKey, |
| 6 | + dump_certificate, dump_privatekey) |
| 7 | + |
| 8 | + |
| 9 | +@dataclass(frozen=True) |
| 10 | +class SelfSignedCertificate: |
| 11 | + host: str = "0.0.0.0" |
| 12 | + bits: int = 2048 |
| 13 | + country: str = "CA" |
| 14 | + state: str = "British Columbia" |
| 15 | + locality: str = "Vancouver" |
| 16 | + organization: str = "Real Python" |
| 17 | + organizational_unit: str = "Development" |
| 18 | + serial_number: int = 1 |
| 19 | + expires_on: int = 365 * 24 * 60 * 60 |
| 20 | + |
| 21 | + @property |
| 22 | + def path(self) -> Path: |
| 23 | + key_pair = PKey() |
| 24 | + key_pair.generate_key(TYPE_RSA, self.bits) |
| 25 | + |
| 26 | + certificate = X509() |
| 27 | + |
| 28 | + subject = certificate.get_subject() |
| 29 | + subject.CN = self.host |
| 30 | + subject.C = self.country |
| 31 | + subject.ST = self.state |
| 32 | + subject.L = self.locality |
| 33 | + subject.O = self.organization |
| 34 | + subject.OU = self.organizational_unit |
| 35 | + |
| 36 | + certificate.set_serial_number(self.serial_number) |
| 37 | + certificate.gmtime_adj_notBefore(0) |
| 38 | + certificate.gmtime_adj_notAfter(self.expires_on) |
| 39 | + certificate.set_issuer(subject) |
| 40 | + certificate.set_pubkey(key_pair) |
| 41 | + certificate.sign(key_pair, "sha256") |
| 42 | + |
| 43 | + with tempfile.NamedTemporaryFile(delete=False) as file: |
| 44 | + file.write(dump_privatekey(FILETYPE_PEM, key_pair)) |
| 45 | + file.write(dump_certificate(FILETYPE_PEM, certificate)) |
| 46 | + |
| 47 | + return Path(file.name) |
0 commit comments