1
1
Fork 0
mirror of https://github.com/pypa/pip synced 2023-12-13 21:30:23 +01:00
pip/tests/lib/certs.py
Paul Ganssle f612503035
Remove uses of utcnow in non-vendored code (#12006)
* Remove reference to utcnow

This cleans up some of the datetime handling in the self check.

Note that this changes the format of the state file, since the datetime
now uses ``.isoformat()`` instead of ``.strftime``. Reading an outdated
state file will still work on Python 3.11+, but not on earlier versions.

* Use aware datetime object in x509.CertificateBuilder
2023-08-31 09:28:31 +01:00

47 lines
1.5 KiB
Python

from datetime import datetime, timedelta, timezone
from typing import Tuple
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
def make_tls_cert(hostname: str) -> Tuple[x509.Certificate, rsa.RSAPrivateKey]:
key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
subject = issuer = x509.Name(
[
x509.NameAttribute(NameOID.COMMON_NAME, hostname),
]
)
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.now(timezone.utc))
.not_valid_after(datetime.now(timezone.utc) + timedelta(days=10))
.add_extension(
x509.SubjectAlternativeName([x509.DNSName(hostname)]),
critical=False,
)
.sign(key, hashes.SHA256(), default_backend())
)
return cert, key
def serialize_key(key: rsa.RSAPrivateKey) -> bytes:
return key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
def serialize_cert(cert: x509.Certificate) -> bytes:
return cert.public_bytes(serialization.Encoding.PEM)