"""Utility methods for private key generation and hash algorithm retrieval."""from__future__importannotationsfromtypingimportTYPE_CHECKINGfromcryptography.hazmat.primitivesimporthashesfromcryptography.hazmat.primitives.asymmetricimportec,rsafromdjango.dbimportmodelsfromtrustpoint_core.oidimportKeyPairGenerator,NamedCurve,PublicKeyAlgorithmOid,PublicKeyInfofromtrustpoint_core.serializerimportPrivateKeySerializerifTYPE_CHECKING:fromtrustpoint_core.crypto_typesimportPrivateKeyfrompki.models.domainimportDomainModel
[docs]classAutoGenPkiKeyAlgorithm(models.TextChoices):"""The key algorithms supported by the AutoGenPKI."""
# omitting the rest of the choices as an example that Auto Gen PKI doesn't have to support all key algorithms
[docs]defto_public_key_info(self)->PublicKeyInfo:"""Gets the corresponding public key info for the key algorithm."""ifself.value==AutoGenPkiKeyAlgorithm.RSA2048:returnPublicKeyInfo(public_key_algorithm_oid=PublicKeyAlgorithmOid.RSA,key_size=2048)ifself.value==AutoGenPkiKeyAlgorithm.RSA4096:returnPublicKeyInfo(public_key_algorithm_oid=PublicKeyAlgorithmOid.RSA,key_size=4096)ifself.value==AutoGenPkiKeyAlgorithm.SECP256R1:returnPublicKeyInfo(public_key_algorithm_oid=PublicKeyAlgorithmOid.ECC,named_curve=NamedCurve.SECP256R1)exc_msg=f'Unsupported key algorithm type for AutoGenPKI: {self.value}'raiseValueError(exc_msg)
[docs]classKeyGenerator:"""Utility class for generating private keys."""@staticmethod
[docs]defgenerate_private_key_for_public_key_info(key_info:PublicKeyInfo)->PrivateKeySerializer:"""Generates a private key for a public key info. Returns: The generated private key. """returnKeyPairGenerator.generate_key_pair_for_public_key_info(key_info)
@staticmethod
[docs]defgenerate_private_key(domain:DomainModel)->PrivateKeySerializer:"""Generates a key pair of the type corresponding to the domain model. Args: domain: The domain to consider. Returns: The generated private key / key pair serializer. """issuing_ca_cert=domain.issuing_ca.credential.get_certificate_serializer().as_crypto()returnPrivateKeySerializer(KeyPairGenerator.generate_key_pair_for_certificate(issuing_ca_cert))
[docs]classCryptographyUtils:"""Utilities methods for cryptography corresponding to Trustpoint models."""@staticmethod
[docs]defget_hash_algorithm_for_private_key(private_key:PrivateKey)->hashes.HashAlgorithm:"""Gets a suitable hash algorithm for a given private key. Args: private_key: The private key to consider. Returns: The hash algorithm to use. """ifisinstance(private_key,rsa.RSAPrivateKey):returnhashes.SHA256()ifisinstance(private_key,ec.EllipticCurvePrivateKey):ifisinstance(private_key.curve,ec.SECP256R1):returnhashes.SHA256()ifisinstance(private_key.curve,ec.SECP384R1):returnhashes.SHA384()err_msg='A suitable hash algorithm is not yet specified for the given private key type.'raiseValueError(err_msg)