Source code for s365b.setup.certs
"""Self-signed certificates for app registration credentials."""
from __future__ import annotations
import base64
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
@dataclass(frozen=True, slots=True)
[docs]
class AppCertificate:
"""A key pair and certificate for one app registration.
Attributes:
private_key_pem: PKCS#8 PEM private key (store encrypted).
certificate_pem: PEM certificate (public; uploaded to Entra).
thumbprint: SHA-1 thumbprint as Entra shows it (hex).
not_after: Expiry.
der_base64: Certificate DER, base64, as Graph ``keyCredentials`` wants.
"""
[docs]
def new_certificate(common_name: str, *, days: int = 365) -> AppCertificate:
"""Generate an RSA-3072 key and a self-signed certificate.
Args:
common_name: Certificate subject CN (shown in the Entra portal).
days: Validity in days.
Returns:
The certificate material.
"""
key = rsa.generate_private_key(public_exponent=65537, key_size=3072)
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)])
now = datetime.now(UTC)
cert = (
x509.CertificateBuilder()
.subject_name(name)
.issuer_name(name)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - timedelta(minutes=5))
.not_valid_after(now + timedelta(days=days))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.sign(key, hashes.SHA256())
)
der = cert.public_bytes(serialization.Encoding.DER)
return AppCertificate(
private_key_pem=key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
).decode(),
certificate_pem=cert.public_bytes(serialization.Encoding.PEM).decode(),
thumbprint=cert.fingerprint(hashes.SHA1()).hex(), # noqa: S303 - Entra thumbprints are SHA-1
not_after=cert.not_valid_after_utc,
der_base64=base64.b64encode(der).decode(),
)