| 22 | |
| 23 | # https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate |
| 24 | def generate_keys(): |
| 25 | folder = Path(__file__).parent |
| 26 | |
| 27 | key = rsa.generate_private_key( |
| 28 | public_exponent=65537, |
| 29 | key_size=2048, |
| 30 | backend=default_backend(), |
| 31 | ) |
| 32 | (folder / "localhost.key").write_bytes( |
| 33 | key.private_bytes( |
| 34 | encoding=Encoding.PEM, |
| 35 | format=PrivateFormat.TraditionalOpenSSL, |
| 36 | encryption_algorithm=NoEncryption(), |
| 37 | ), |
| 38 | ) |
| 39 | |
| 40 | subject = issuer = Name( |
| 41 | [ |
| 42 | NameAttribute(NameOID.COUNTRY_NAME, "IE"), |
| 43 | NameAttribute(NameOID.ORGANIZATION_NAME, "Scrapy"), |
| 44 | NameAttribute(NameOID.COMMON_NAME, "localhost"), |
| 45 | ] |
| 46 | ) |
| 47 | cert = ( |
| 48 | CertificateBuilder() |
| 49 | .subject_name(subject) |
| 50 | .issuer_name(issuer) |
| 51 | .public_key(key.public_key()) |
| 52 | .serial_number(random_serial_number()) |
| 53 | .not_valid_before(datetime.now(tz=timezone.utc)) |
| 54 | .not_valid_after(datetime.now(tz=timezone.utc) + timedelta(days=10)) |
| 55 | .add_extension( |
| 56 | SubjectAlternativeName([DNSName("localhost")]), |
| 57 | critical=False, |
| 58 | ) |
| 59 | .sign(key, SHA256(), default_backend()) |
| 60 | ) |
| 61 | (folder / "localhost.crt").write_bytes(cert.public_bytes(Encoding.PEM)) |