def main(): # Create or load a root CA key pair print('\nLoading root CA key') root_ca_priv_key = load_or_create_key(ROOT_CA_KEY_FILENAME) # Create root CA certificate print('\nGenerating self-signed root CA certificate') builder = x509.CertificateBuilder() builder = builder.serial_number(random_cert_sn(16)) # Please note that the name of the root CA is also part of the signer certificate and thus, it's # part of certificate definition in the SAMG55 firmware (g_cert_elements_1_signer). If this name is # changed, it will also need to be changed in the firmware. The cert2certdef.py utility script can # help with regenerating the cert_def_1_signer.c file after making changes. builder = builder.issuer_name( x509.Name([ x509.NameAttribute(x509.oid.NameOID.ORGANIZATION_NAME, u'Example Inc'), x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, u'Example Root CA') ])) builder = builder.not_valid_before(datetime.datetime.now(tz=pytz.utc)) builder = builder.not_valid_after( builder._not_valid_before.replace(year=builder._not_valid_before.year + 25)) builder = builder.subject_name(builder._issuer_name) builder = builder.public_key(root_ca_priv_key.public_key()) builder = builder.add_extension(x509.SubjectKeyIdentifier.from_public_key( root_ca_priv_key.public_key()), critical=False) builder = builder.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) # Self-sign certificate root_ca_cert = builder.sign(private_key=root_ca_priv_key, algorithm=hashes.SHA256(), backend=crypto_be) # Write root CA certificate to file with open(ROOT_CA_CERT_FILENAME, 'wb') as f: print(' Saving to ' + f.name) f.write(root_ca_cert.public_bytes(encoding=serialization.Encoding.PEM)) print('\nDone')
def generate_x509_cert_issuer_auth(issuer_key_private): issuer = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, u"State Of Utopia"), ]) subject = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, u"State Of Utopia Issuing Authority Signing Key"), ]) builder = ( x509.CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(issuer_key_private.public_key()).serial_number( 42).not_valid_before(datetime.datetime.utcnow()) # Our certificate will be valid for 5 years .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=365 * 5))) cert = builder.sign(issuer_key_private, hashes.SHA256()) cert_bytes = cert.public_bytes(serialization.Encoding.DER) # print("cert_bytes: %s" % binascii.hexlify(cert_bytes)) return cert_bytes
def _generate_root(private_key=None, algorithm=hashes.SHA256()): from cryptography.hazmat.backends.openssl.backend import backend if private_key is None: private_key = EC_KEY_SECP256R1.private_key(backend) subject = x509.Name([ x509.NameAttribute(x509.NameOID.COUNTRY_NAME, "US"), x509.NameAttribute(x509.NameOID.COMMON_NAME, "Cryptography CA"), ]) builder = (x509.CertificateBuilder().serial_number(123456789).issuer_name( subject).subject_name(subject).public_key( private_key.public_key()).not_valid_before( datetime.datetime.now()).not_valid_after( datetime.datetime.now() + datetime.timedelta(days=3650))) cert = builder.sign(private_key, algorithm, backend) return cert, private_key
def ca_certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate: b = x509.CertificateBuilder() name = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Commandment"), x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"), ]) cert = b.serial_number(1).issuer_name(name).subject_name(name).public_key( private_key.public_key()).not_valid_before( datetime.datetime.utcnow()).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=10)).add_extension( x509.BasicConstraints(ca=True, path_length=None), True).sign(private_key, hashes.SHA256(), default_backend()) return cert
def generate_self_signed_certificate(common_name="Test", valid_from=None, valid_to=None): valid_from = valid_from if valid_from else datetime.datetime.utcnow() valid_to = valid_to if valid_to else valid_from + datetime.timedelta( days=1) private_key = ec.generate_private_key(ec.SECP256R1(), default_backend()) public_key = private_key.public_key() subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]) return (x509.CertificateBuilder().public_key(public_key).subject_name( subject).issuer_name( subject) # Same as subject on self-signed certificate. .serial_number(x509.random_serial_number()).not_valid_before( valid_from).not_valid_after(valid_to)).sign( private_key, hashes.SHA256(), default_backend())
def get_node_tls_cert_pem(key, node_id_raw): b = x509.CertificateBuilder() b = b.serial_number(x509.random_serial_number()) b = b.public_key(key.public_key()) cn = get_node_tls_cn(node_id_raw) x509_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)]) b = b.subject_name(x509_name) b = b.issuer_name(x509_name) now = datetime.now() b = b.not_valid_before(now - timedelta(days=1)) b = b.not_valid_after(now + timedelta(days=365 * 10)) cert = b.sign(private_key=key, algorithm=hashes.SHA256(), backend=default_backend()) cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM) return cert_pem.decode('ascii')
def make_cert(name): key = ec.generate_private_key(ec.SECP256R1()) subject = x509.Name( [ x509.NameAttribute(x509.NameOID.COMMON_NAME, name), ] ) now = datetime.utcnow() cert = ( x509.CertificateBuilder() .subject_name(subject) .issuer_name(subject) .public_key(key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(now) .not_valid_after(now) .sign(key, hashes.SHA256()) ) return (key, cert)
def generate_certificate(key: ec.EllipticCurvePrivateKey) -> x509.Certificate: name = x509.Name( [ x509.NameAttribute( x509.NameOID.COMMON_NAME, binascii.hexlify(os.urandom(16)).decode("ascii"), ) ] ) builder = ( x509.CertificateBuilder() .subject_name(name) .issuer_name(name) .public_key(key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(datetime.datetime.utcnow() - datetime.timedelta(days=1)) .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=30)) ) return builder.sign(key, hashes.SHA256(), default_backend())
def test_sign_with_dsa_private_key_is_unsupported(self): private_key = DSA_KEY_2048.private_key(backend) builder = x509.CertificateBuilder() builder = builder.subject_name( x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')]) ).issuer_name( x509.Name([x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US')]) ).serial_number( 1 ).public_key( private_key.public_key() ).not_valid_before( datetime.datetime(2002, 1, 1, 12, 1) ).not_valid_after( datetime.datetime(2032, 1, 1, 12, 1) ) with pytest.raises(NotImplementedError): builder.sign(private_key, hashes.SHA512(), backend)
def _create_self_signed_certificate(self, private_key): issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"), x509.NameAttribute(NameOID.COMMON_NAME, u"Test Certificate"), ]) cert_builder = x509.CertificateBuilder( issuer_name=issuer, subject_name=issuer, public_key=private_key.public_key(), serial_number=x509.random_serial_number(), not_valid_before=datetime.utcnow(), not_valid_after=datetime.utcnow() + timedelta(days=10) ) cert = cert_builder.sign(private_key, hashes.SHA256(), default_backend()) return cert
def generate_self_signed_certificate( self, slot, public_key, common_name, valid_from, valid_to, touch_callback=None): algorithm = ALGO.from_public_key(public_key) builder = x509.CertificateBuilder() builder = builder.public_key(public_key) builder = builder.subject_name( x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name), ])) # Same as subject on self-signed certificates. builder = builder.issuer_name( x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name), ])) # x509.random_serial_number added in cryptography 1.6 serial = int_from_bytes(os.urandom(20), 'big') >> 1 builder = builder.serial_number(serial) builder = builder.not_valid_before(valid_from) builder = builder.not_valid_after(valid_to) try: cert = self.sign_cert_builder( slot, algorithm, builder, touch_callback) except APDUError as e: logger.error('Failed to generate certificate for slot %s', slot, exc_info=e) raise # Verify that the public key used in the certificate # is from the same keypair as the private key. cert_signature = cert.signature cert_bytes = cert.tbs_certificate_bytes if isinstance(public_key, rsa.RSAPublicKey): public_key.verify( cert_signature, cert_bytes, padding.PKCS1v15(), cert.signature_hash_algorithm) elif isinstance(public_key, ec.EllipticCurvePublicKey): public_key.verify( cert_signature, cert_bytes, ec.ECDSA(cert.signature_hash_algorithm)) self.import_certificate(slot, cert)
def generate_root(self) -> Tuple[bytes, bytes]: if self.expiry_date is None: expiry_date = self.default_root_expiry_date else: expiry_date = self.expiry_date rsa_key_pair = self._private_key() x509_details = self.generate_x509_details() cert = x509.CertificateBuilder() \ .subject_name(x509_details) \ .issuer_name(x509_details) \ .public_key(rsa_key_pair.public_key()) \ .serial_number(x509.random_serial_number()) \ .not_valid_before(datetime.datetime.utcnow()) \ .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=expiry_date)) \ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) \ .sign(rsa_key_pair, hashes.SHA256(), default_backend()) return self.to_bytes(rsa_key_pair, cert)
def setup_certificate(workspace): """Generate a self-signed certificate for nginx. :param workspace: path of folder where to put the certificate :return: tuple containing the key path and certificate path :rtype: `tuple` """ # Generate key # See comment on cryptography import about type: ignore private_key = rsa.generate_private_key( # type: ignore public_exponent=65537, key_size=2048, backend=default_backend() ) subject = issuer = x509.Name([ x509.NameAttribute(x509.NameOID.COMMON_NAME, u'nginx.wtf') ]) certificate = x509.CertificateBuilder().subject_name( subject ).issuer_name( issuer ).public_key( private_key.public_key() ).serial_number( 1 ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=1) ).sign(private_key, hashes.SHA256(), default_backend()) key_path = os.path.join(workspace, 'cert.key') with open(key_path, 'wb') as file_handle: file_handle.write(private_key.private_bytes( # type: ignore encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() )) cert_path = os.path.join(workspace, 'cert.pem') with open(cert_path, 'wb') as file_handle: file_handle.write(certificate.public_bytes(serialization.Encoding.PEM)) return key_path, cert_path
def __init__(self, Create_PrivKey = True, Path2Key = None): ''' :param Create_PrivKey: True if we want to generate a private key, False if we dont want to. :param Path2Key: If it is provided reads the private key ''' self.cert = x509.CertificateBuilder() # Creamos el objeto certificado # Si nos proporcionan una clave privada no hace falta crearla self.Path = Path2Key self.Create_Priv_Key = Create_PrivKey if self.Create_Priv_Key == True: self.key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend()) # En caso de que se llame al constructor con la ruta a la clave privada else: if self.Path != None: self.key = serialization.load_pem_private_key(str.encode(open(self.Path).read()), password = None, backend = default_backend())
def generate_self_signed_certificate(private_key, certificate_path): """Generate a self signed certificate using a generated private key. The certificate will be created in 'CONFIG_PATH/ssl/server.crt'. Parameters ---------- private_key : RSAPrivateKey Private key. certificate_path : str Path where the self signed certificate will be generated. """ # Generate private key # Various details about who we are. For a self-signed certificate the # subject and issuer are always the same. subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Wazuh"), x509.NameAttribute(NameOID.COMMON_NAME, u"wazuh.com"), ]) cert = x509.CertificateBuilder().subject_name( subject ).issuer_name( issuer ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( # Our certificate will be valid for 10 days datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName([x509.DNSName(u"localhost")]), critical=False, # Sign our certificate with our private key ).sign(private_key, hashes.SHA256(), crypto_default_backend()) # Write our certificate out to disk. with open(certificate_path, 'wb') as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) os.chmod(certificate_path, 0o400)
def ClientCertFromCSR(cls, csr): """Creates a new cert for the given common name. Args: csr: A CertificateSigningRequest. Returns: The signed cert. """ builder = x509.CertificateBuilder() # Use the client CN for a cert serial_id. This will ensure we do # not have clashing cert id. common_name = csr.GetCN() serial = int(common_name.split(".")[1], 16) builder = builder.serial_number(serial) builder = builder.subject_name( x509.Name([ x509.NameAttribute(oid.NameOID.COMMON_NAME, str(common_name)) ])) now = rdfvalue.RDFDatetime.Now() now_plus_year = now + rdfvalue.Duration.From(52, rdfvalue.WEEKS) builder = builder.not_valid_after(now_plus_year.AsDatetime()) now_minus_ten = now - rdfvalue.Duration.From(10, rdfvalue.SECONDS) builder = builder.not_valid_before(now_minus_ten.AsDatetime()) # TODO(user): dependency loop with # grr/core/grr_response_core/config/client.py. # pylint: disable=protected-access ca_cert = config_lib._CONFIG["CA.certificate"] # pylint: enable=protected-access builder = builder.issuer_name(ca_cert.GetIssuer()) builder = builder.public_key(csr.GetPublicKey().GetRawPublicKey()) # TODO(user): dependency loop with # grr/core/grr_response_core/config/client.py. # pylint: disable=protected-access ca_key = config_lib._CONFIG["PrivateKeys.ca_key"] # pylint: enable=protected-access return RDFX509Cert( builder.sign(private_key=ca_key.GetRawPrivateKey(), algorithm=hashes.SHA256(), backend=openssl.backend))
def issue_self_signed_certificate(domains, private_key, logger): # Generates a self-signed certificate. from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.x509.oid import NameOID from cryptography.x509 import DNSName import datetime import uuid logger("Issuing self-signed certificate.") import sys if sys.version_info < (3,): # In Py2, pyca requires the CN to be a unicode instance. domains = [domain.decode("ascii") for domain in domains] # https://cryptography.io/en/latest/x509/reference/ one_day = datetime.timedelta(days=1) duration = datetime.timedelta(days=31) builder = x509.CertificateBuilder() builder = builder.subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, domains[0]), ])) builder = builder.issuer_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, domains[0]), ])) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + duration) builder = builder.serial_number(int(uuid.uuid4())) builder = builder.public_key(private_key.public_key()) builder = builder.add_extension( x509.BasicConstraints(ca=False, path_length=None), critical=True, ) if len(domains) > 1: builder = builder.add_extension(x509.SubjectAlternativeName([ x509.DNSName(domain) for domain in domains]), critical=False) certificate = builder.sign( private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend() ) return (cert_to_pem(certificate), []) # no chain
def bootstrap_ca( days_valid: int = 3650, common_name: str = "resoto Root CA", organization_name: str = "Some Engineering Inc.", locality_name: str = "San Francisco", state_or_province_name: str = "California", country_name: str = "US", path_length: int = 2, ) -> Tuple[RSAPrivateKey, Certificate]: ca_key = gen_rsa_key() subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, country_name), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state_or_province_name), x509.NameAttribute(NameOID.LOCALITY_NAME, locality_name), x509.NameAttribute(NameOID.ORGANIZATION_NAME, organization_name), x509.NameAttribute(NameOID.COMMON_NAME, common_name), ]) ca_cert = ( x509.CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(ca_key.public_key()).serial_number( x509.random_serial_number()). not_valid_before(datetime.now(tz=timezone.utc)).not_valid_after( datetime.now(tz=timezone.utc) + timedelta(days=days_valid)).add_extension( x509.BasicConstraints(ca=True, path_length=path_length), critical=True).add_extension( x509.KeyUsage( digital_signature=False, key_encipherment=False, key_cert_sign= True, # CA Cert is only allowed to sign other certs key_agreement=False, content_commitment=False, data_encipherment=False, crl_sign=True, # and cert revocation lists encipher_only=False, decipher_only=False, ), critical=True, # KeyUsage extension is critical to support ).sign(ca_key, hashes.SHA256(), default_backend())) return ca_key, ca_cert
def generate_root_cert( path: Path, country: str, state: str, locality: str, org_name: str, common_name: str ) -> typing.Tuple["cryptography.x509.Certificate", rsa.RSAPrivateKey]: """Generates a self-signed CA root certificate (RSA). :param path: The path of the generated private key. The resulting certificate will be saved to the same directory as :code:`root.crt`. :param country: The requested *country name* in the certificate. :param state: The requested *state or province name* in the certificate. :param locality: The requested *locality name* in the certificate. :param org_name: The requested *organization name* in the certificate. :param common_name: The requested *common name* in the certificate. :return: The resulting root certificate and corresponding private key. """ root_key = generate_rsa_key(path) subject = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, country), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state), x509.NameAttribute(NameOID.LOCALITY_NAME, locality), x509.NameAttribute(NameOID.ORGANIZATION_NAME, org_name), x509.NameAttribute(NameOID.LOCALITY_NAME, common_name), ]) root_cert_builder = (x509.CertificateBuilder().subject_name( subject).issuer_name(subject).public_key( root_key.public_key()).serial_number( x509.random_serial_number()).not_valid_before( datetime.utcnow()).not_valid_after( datetime.utcnow() + timedelta(days=365 * 4)).add_extension( x509.BasicConstraints(ca=True, path_length=None), critical=True)) root_cert = root_cert_builder.sign(root_key, hashes.SHA256()) pem = root_cert.public_bytes(serialization.Encoding.PEM) with open(path.parent / "root.crt", "wb") as pem_out: pem_out.write(pem) return root_cert, root_key
def create_CA(path, path_key, CA_subj_dict): '''Creating CA dirpath - path to directory, where CA will be placed CA_subj_dict - dict, like this CA_subj_dict={'Country':u'PL', ...}''' private_key_CA = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) public_key_CA = private_key_CA.public_key() with open(path_key, 'wb') as f: f.write( private_key_CA.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption( b"password"))) CA_subject = [ x509.NameAttribute(NameOID.COUNTRY_NAME, CA_subj_dict['Country']), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, CA_subj_dict['State']), x509.NameAttribute(NameOID.LOCALITY_NAME, CA_subj_dict['Locality']), x509.NameAttribute(NameOID.ORGANIZATION_NAME, CA_subj_dict['Organization']), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, CA_subj_dict['OU']), x509.NameAttribute(NameOID.COMMON_NAME, CA_subj_dict['CN']) ] CA_cert = x509.CertificateBuilder().subject_name(x509.Name(CA_subject)) CA_cert = CA_cert.issuer_name(x509.Name(CA_subject)) CA_cert = CA_cert.public_key(public_key_CA) CA_cert = CA_cert.serial_number(x509.random_serial_number()) CA_cert = CA_cert.not_valid_before(datetime.datetime.utcnow()) CA_cert = CA_cert.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=10)) CA_cert = CA_cert.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) CA_cert = CA_cert.sign(private_key_CA, hashes.SHA256(), default_backend()) with open(path, 'wb') as CAcert: CAcert.write(CA_cert.public_bytes(serialization.Encoding.PEM)) return private_key_CA, CA_subject, CA_cert
def generate_adhoc_ssl_pair( cn: t.Optional[str] = None, ) -> t.Tuple["Certificate", "RSAPrivateKeyWithSerialization"]: try: from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa except ImportError: raise TypeError("Using ad-hoc certificates requires the cryptography library.") backend = default_backend() pkey = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=backend ) # pretty damn sure that this is not actually accepted by anyone if cn is None: cn = "*" subject = x509.Name( [ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dummy Certificate"), x509.NameAttribute(NameOID.COMMON_NAME, cn), ] ) backend = default_backend() cert = ( x509.CertificateBuilder() .subject_name(subject) .issuer_name(subject) .public_key(pkey.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(dt.now(timezone.utc)) .not_valid_after(dt.now(timezone.utc) + timedelta(days=365)) .add_extension(x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]), critical=False) .add_extension(x509.SubjectAlternativeName([x509.DNSName(cn)]), critical=False) .sign(pkey, hashes.SHA256(), backend) ) return cert, pkey
def __enter__(self): 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 subject = issuer = x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, "localhost")]) with contextlib.ExitStack() as stack: key = rsa.generate_private_key(public_exponent=65537, key_size=1024, backend=default_backend()) key_file = stack.enter_context(tempfile.NamedTemporaryFile()) key_file.write( key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) ) key_file.flush() cert = ( x509.CertificateBuilder() .subject_name(subject) .issuer_name(issuer) .public_key(key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(datetime.datetime.utcnow()) .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=1)) .add_extension( x509.SubjectAlternativeName([x509.DNSName("localhost"), x509.DNSName("127.0.0.1")]), critical=False ) .sign(key, hashes.SHA256(), default_backend()) ) cert_file = stack.enter_context(tempfile.NamedTemporaryFile()) cert_file.write(cert.public_bytes(serialization.Encoding.PEM)) cert_file.flush() self._key_file, self._cert_file = key_file, cert_file stack.pop_all() return self
def generate_self_signed_cert(hostname, server_key, ip_addresses=None): """ Generates self signed certificate for a hostname, and optional IP addresses. """ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, hostname)]) alt_names = [x509.DNSName(hostname)] if ip_addresses: for addr in ip_addresses: alt_names.append(x509.DNSName(addr)) alt_names.append(x509.IPAddress(ipaddress.ip_address(addr))) ca_crt = x509.CertificateBuilder().subject_name(name).issuer_name( name).public_key(server_key.public_key()).serial_number(uuid.uuid4( ).int).not_valid_before(datetime.datetime.utcnow()).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365 * 100)).add_extension( extension=x509.KeyUsage(digital_signature=True, key_encipherment=True, key_cert_sign=True, crl_sign=True, content_commitment=True, data_encipherment=False, key_agreement=False, encipher_only=False, decipher_only=False), critical=False).add_extension( extension=x509.BasicConstraints(ca=True, path_length=0), critical=False).add_extension( extension=x509.SubjectKeyIdentifier.from_public_key( server_key.public_key()), critical=False).add_extension( extension=x509.AuthorityKeyIdentifier. from_issuer_public_key(server_key.public_key()), critical=False).add_extension( extension=x509.SubjectAlternativeName( alt_names), critical=False).sign(private_key=server_key, algorithm=hashes.SHA256(), backend=default_backend()) ca_cert_pem = ca_crt.public_bytes(encoding=serialization.Encoding.PEM) return ca_cert_pem
def create_x509_cert(privkey, pubkey, subject_info, issuer_info, days): """Main cert creation code. """ if not isinstance(subject_info, CertInfo): info = CertInfo() info.load_from_existing(subject_info) subject_info = info if not isinstance(issuer_info, CertInfo): info = CertInfo() info.load_from_existing(issuer_info) issuer_info = info dt_now = datetime.utcnow() dt_start = dt_now - timedelta(hours=1) dt_end = dt_now + timedelta(days=days) builder = (x509.CertificateBuilder() .subject_name(subject_info.get_name()) .issuer_name(issuer_info.get_name()) .not_valid_before(dt_start) .not_valid_after(dt_end) .serial_number(int(uuid.uuid4())) .public_key(pubkey)) builder = subject_info.install_extensions(builder) # SubjectKeyIdentifier ext = x509.SubjectKeyIdentifier.from_public_key(pubkey) builder = builder.add_extension(ext, critical=False) # AuthorityKeyIdentifier ext = x509.AuthorityKeyIdentifier.from_issuer_public_key(privkey.public_key()) builder = builder.add_extension(ext, critical=False) # IssuerAlternativeName if issuer_info.san: ext = x509.IssuerAlternativeName(issuer_info.get_san_gnames()) builder = builder.add_extension(ext, critical=False) # final cert cert = builder.sign(private_key=privkey, algorithm=SHA256(), backend=get_backend()) return cert
def make_key_cert_pair(self, hostname, ip): private_key = rsa.generate_private_key( backend=crypto_default_backend(), public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() builder = x509.CertificateBuilder() builder = builder.subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, hostname), ])) builder = builder.issuer_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, hostname), ])) builder = builder.not_valid_before(datetime.datetime.today() - day) builder = builder.not_valid_after(datetime.datetime.today() + EXPIRE_TIME) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(public_key) builder = builder.add_extension( x509.SubjectAlternativeName( [x509.DNSName(ip)] ), critical=True ) certificate = builder.sign( private_key=private_key, algorithm=hashes.SHA256(), backend=crypto_default_backend() ) ser_private_key = private_key.private_bytes( crypto_serialization.Encoding.PEM, crypto_serialization.PrivateFormat.PKCS8, crypto_serialization.NoEncryption()) ser_public_key = certificate.public_bytes( crypto_serialization.Encoding.PEM ) return ser_private_key, ser_public_key
def generateCertAndKeys(): one_day = datetime.timedelta(1, 0, 0) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) public_key = private_key.public_key() builder = x509.CertificateBuilder() builder = builder.subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, u'Common Name'), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Organization Name'), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Unit Name'), ])) builder = builder.issuer_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, u'Common Name'), ])) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime(2028, 8, 2)) builder = builder.serial_number(int(uuid.uuid4())) builder = builder.public_key(public_key) builder = builder.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True,) certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA256(),backend=default_backend()) print(isinstance(certificate, x509.Certificate)) certName = "ca.crt" with open("ca.key", "wb") as f: f.write(private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() )) with open(certName, "wb") as f: f.write(certificate.public_bytes( encoding=serialization.Encoding.PEM, )) return certName, public_key, private_key, certificate
def generate_node_certificates(private_key, public_key): today = datetime.datetime.today() one_day = datetime.timedelta(1, 0, 0) address = node_public_address(public_key) builder = x509.CertificateBuilder() builder = builder.not_valid_before(today) # TODO: Where's documentation of the decision to make keys valid for 1 year only? builder = builder.not_valid_after(today + 365 * one_day) issuer = x509.Name([ x509.NameAttribute(x509.NameOID.COUNTRY_NAME, "US"), x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, "CA"), x509.NameAttribute(x509.NameOID.LOCALITY_NAME, "San-Diego"), x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, "CasperLabs, LLC"), x509.NameAttribute(x509.NameOID.ORGANIZATIONAL_UNIT_NAME, "IT Department"), x509.NameAttribute(x509.NameOID.COMMON_NAME, address), ]) builder = builder.issuer_name(issuer) builder = builder.subject_name(issuer) builder = builder.public_key(public_key) builder = builder.serial_number(x509.random_serial_number()) ski = x509.SubjectKeyIdentifier.from_public_key(public_key) builder = builder.add_extension(ski, critical=False) builder = builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski), critical=False, ) builder = builder.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend()) cert_pem = certificate.public_bytes(encoding=serialization.Encoding.PEM) key_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ) return cert_pem, key_pem
def generate_certificate(self): """(Re-)Generate certificate.""" try: cert_builder = x509.CertificateBuilder() cert_builder = cert_builder.subject_name(self.csr.subject) cert_builder = cert_builder.issuer_name(self.csr.subject) cert_builder = cert_builder.serial_number(self.serial_number) cert_builder = cert_builder.not_valid_before(self.notBefore) cert_builder = cert_builder.not_valid_after(self.notAfter) cert_builder = cert_builder.public_key( self.privatekey.public_key()) has_ski = False for extension in self.csr.extensions: if isinstance(extension.value, x509.SubjectKeyIdentifier): if self.create_subject_key_identifier == 'always_create': continue has_ski = True cert_builder = cert_builder.add_extension( extension.value, critical=extension.critical) if not has_ski and self.create_subject_key_identifier != 'never_create': cert_builder = cert_builder.add_extension( x509.SubjectKeyIdentifier.from_public_key( self.privatekey.public_key()), critical=False) except ValueError as e: raise CertificateError(str(e)) try: certificate = cert_builder.sign(private_key=self.privatekey, algorithm=self.digest, backend=default_backend()) except TypeError as e: if str( e ) == 'Algorithm must be a registered hash algorithm.' and self.digest is None: self.module.fail_json( msg= 'Signing with Ed25519 and Ed448 keys requires cryptography 2.8 or newer.' ) raise self.cert = certificate
def _generate_cert(server_name, not_valid_before, not_valid_after, key=RSA_KEY_512_RAW): """ Generate a self-signed certificate for test purposes. :param str server_name: The SAN the certificate should have. :param ~datetime.datetime not_valid_before: Valid from this moment. :param ~datetime.datetime not_valid_after: Expiry time. :param key: The private key. :rtype: `str` :return: The certificate in PEM format. """ common_name = ( u'san.too.long.invalid' if len(server_name) > 64 else server_name) name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, common_name)]) cert = ( x509.CertificateBuilder() .subject_name(name) .issuer_name(name) .not_valid_before(not_valid_before) .not_valid_after(not_valid_after) .serial_number(int(uuid.uuid4())) .public_key(key.public_key()) .add_extension( x509.SubjectAlternativeName([x509.DNSName(server_name)]), critical=False) .sign( private_key=key, algorithm=hashes.SHA256(), backend=default_backend()) ) return [ Certificate( cert.public_bytes(serialization.Encoding.PEM)), RSAPrivateKey( key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption())), ]
def build_certificate(cls, parameters, payload, key, signer_pub_key, org_name): name_oid = [ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org_name), x509.NameAttribute(NameOID.USER_ID, signer_pub_key) ] for k, v in parameters.items(): if k in payload.keys(): name_oid.append(x509.NameAttribute(v, payload[k])) subject = issuer = x509.Name(name_oid) not_valid_before, not_valid_after = cls.get_dates_from_payload(payload) return x509.CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(key.public_key()).serial_number( x509.random_serial_number()).not_valid_before( not_valid_before).not_valid_after(not_valid_after).sign( key, hashes.SHA256(), default_backend())