def generate_keys(): folder = os.path.dirname(__file__) key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) with open(os.path.join(folder, 'localhost.key'), "wb") as f: f.write( key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption(), )) subject = issuer = Name([ NameAttribute(NameOID.COUNTRY_NAME, "IE"), NameAttribute(NameOID.ORGANIZATION_NAME, "Scrapy"), NameAttribute(NameOID.COMMON_NAME, "localhost"), ]) cert = (CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(key.public_key()).serial_number( random_serial_number()).not_valid_before( datetime.utcnow()).not_valid_after( datetime.utcnow() + timedelta(days=10)).add_extension( SubjectAlternativeName([DNSName("localhost")]), critical=False, ).sign(key, SHA256(), default_backend())) with open(os.path.join(folder, 'localhost.crt'), "wb") as f: f.write(cert.public_bytes(Encoding.PEM))
def _sign_csr( csr: CertificateSigningRequest, days_valid: int, signing_cert: Certificate, signing_private_key: RSAPrivateKeyWithSerialization, ) -> Certificate: common_name = csr.subject.get_attributes_for_oid( NameOID.COMMON_NAME)[0].value return (_make_cert_builder( csr.subject, days_valid, _rsa_public_key_from_cert_or_csr(csr), ).issuer_name(signing_cert.issuer).add_extension( SubjectAlternativeName([DNSName(common_name)]), critical=False, ).add_extension( BasicConstraints( ca=False, path_length=None, ), critical=True, ).sign( signing_private_key, SHA256(), ))
def _create_x509_certificate( key_der, subject_name ): #type(Union[EllipticCurvePrivateKey,RSAPrivateKey], str) -> Certificate signing_key = serialization.load_der_private_key( key_der, password=None, backend=default_backend()) builder = CertificateBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_name), ])) builder = builder.issuer_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_name), ])) one_day = datetime.timedelta(1, 0, 0) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 30)) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(signing_key.public_key()) builder = builder.add_extension(SubjectAlternativeName( [x509.DNSName(subject_name)]), critical=False) builder = builder.add_extension(BasicConstraints(ca=False, path_length=None), critical=True) return builder.sign(private_key=signing_key, algorithm=hashes.SHA256(), backend=default_backend()).public_bytes( serialization.Encoding.DER)
def selfsigned(key, common_name, san): subject = issuer = Name([ NameAttribute(NameOID.COMMON_NAME, common_name), NameAttribute(NameOID.ORGANIZATION_NAME, "Sanic Org"), ]) cert = (CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(key.public_key()).serial_number( random_serial_number()).not_valid_before( datetime.utcnow()).not_valid_after( datetime.utcnow() + timedelta(days=365.25 * 8)).add_extension( KeyUsage(True, False, False, False, False, False, False, False, False), critical=True, ).add_extension( ExtendedKeyUsage([ ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH, ]), critical=False, ).add_extension( BasicConstraints(ca=True, path_length=None), critical=True, ).add_extension( SubjectAlternativeName([ IPAddress(ip_address(n)) if n[0].isdigit() or ":" in n else DNSName(n) for n in san ]), critical=False, ).sign(key, hashes.SHA256())) return cert
def create_x509_certificate(key_pem, subject_name): # type: (str, str) -> str """ Given an RSA or ECDS private key, create a self-signed X.509 certificate with the specified subject name signed with that key. """ signing_key = serialization.load_pem_private_key(key_pem.encode("ascii"), password=None, backend=default_backend()) builder = CertificateBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_name), ])) builder = builder.issuer_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_name), ])) one_day = datetime.timedelta(1, 0, 0) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 30)) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(signing_key.public_key()) builder = builder.add_extension(SubjectAlternativeName( [x509.DNSName(subject_name)]), critical=False) builder = builder.add_extension(BasicConstraints(ca=False, path_length=None), critical=True) return (builder.sign( private_key=signing_key, algorithm=hashes.SHA256(), backend=default_backend(), ).public_bytes(serialization.Encoding.PEM).decode("ascii"))
def generate_tls_keys(): """ Creates a TLS private key (RSA, 4096 bits, PEM format) and certificate signing request (CSR). """ # Query the user for CSR attributes country = input("Country: ") state = input("State or province: ") locality = input("Locality: ") organization = input("Organization: ") organizational_unit = input("Organizational unit: ") email = input("Email: ") common_name = input("Common name: ") print("Enter any subject alternative names (SANs) you wish to attach to the certificate. Leave blank to continue.") sans = [] while True: san = input("Subject alternative name: ") if san == '': break sans.append(DNSName(san)) # Make sure we can open the output files first private_key_file = open("private.key", "wb") csr_file = open("certificate_signing_request", "wb") # Generate the private key key = generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend()) attributes = [ NameAttribute(NameOID.COUNTRY_NAME, country), NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state), NameAttribute(NameOID.LOCALITY_NAME, locality), NameAttribute(NameOID.ORGANIZATION_NAME, organization), NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, organizational_unit), NameAttribute(NameOID.EMAIL_ADDRESS, email), NameAttribute(NameOID.COMMON_NAME, common_name), ] # Generate the CSR and sign it with the private key csr = CertificateSigningRequestBuilder().subject_name(Name(attributes)) if sans: csr = csr.add_extension(SubjectAlternativeName(sans), critical=False) csr = csr.sign(key, SHA256(), default_backend()) # Write the private key and CSR to disk private_key_file.write(key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption())) csr_file.write(csr.public_bytes(Encoding.PEM)) private_key_file.close() csr_file.close() # Success! print("Successfully generated a private key and certificate signing request.")
def server_cert(server_key, backend): """Generate server certificate.""" subject = issuer = Name([ NameAttribute(NameOID.COMMON_NAME, six.u('localhost')), NameAttribute(NameOID.ORGANIZATION_NAME, six.u('Bob B. Server')) ]) return CertificateBuilder().subject_name(subject).issuer_name( issuer).serial_number(random_serial_number()).public_key( server_key.public_key()).not_valid_before(datetime( 2008, 1, 1)).not_valid_after(datetime(3020, 1, 1)).add_extension( SubjectAlternativeName([DNSName(six.u('localhost'))]), critical=False).sign(server_key, SHA256(), backend)
def client_cert(client_key, backend): """Generate client certificate.""" subject = issuer = Name([ NameAttribute(NameOID.COMMON_NAME, six.u('example.org')), NameAttribute(NameOID.ORGANIZATION_NAME, six.u('Alice A. Client')) ]) return CertificateBuilder().subject_name(subject).issuer_name( issuer).serial_number(random_serial_number()).public_key( client_key.public_key()).not_valid_before(datetime( 3019, 1, 1)).not_valid_after(datetime(3019, 1, 10)).add_extension( SubjectAlternativeName([DNSName(six.u('localhost'))]), critical=False).sign(client_key, SHA256(), backend)
def _generate_certs(path: Union[Path, str], days: int = 3652, key_size: int = 2048, separate_key: bool = False) -> None: # DO NOT USE THIS FOR ANYTHING PRODUCTION RELATED, EVER! # Generate private key # 2048 is the minimum that works as of 3.9 key = rsa.generate_private_key(public_exponent=65537, key_size=key_size) key_file = "key.pem" if separate_key else "cert.pem" key_path = Path(path).joinpath(key_file) with open(key_path, "ab") as f: f.write(key.private_bytes( encoding=serialization.Encoding.PEM, encryption_algorithm=serialization.NoEncryption(), format=serialization.PrivateFormat.TraditionalOpenSSL )) log.debug("Private key generated") # Generate public certificate hostname = socket.gethostname() ip = socket.gethostbyname(hostname) subject = Name([NameAttribute(NameOID.COMMON_NAME, "smtpdfix_cert")]) alt_names = [ DNSName("localhost"), DNSName("localhost.localdomain"), DNSName(hostname), IPAddress(ip_address("127.0.0.1")), IPAddress(ip_address("0.0.0.1")), IPAddress(ip_address("::1")), IPAddress(ip_address(ip)), ] # Set it so the certificate can be a root certificate with # ca=true, path_length=0 means it can only sign itself. constraints = BasicConstraints(ca=True, path_length=0) cert = (CertificateBuilder() .issuer_name(subject) .subject_name(subject) .serial_number(random_serial_number()) .not_valid_before(datetime.utcnow()) .not_valid_after(datetime.utcnow() + timedelta(days=days)) .add_extension(SubjectAlternativeName(alt_names), critical=False) .public_key(key.public_key()) .add_extension(constraints, critical=False) .sign(private_key=key, algorithm=hashes.SHA256())) cert_path = Path(path).joinpath("cert.pem") with open(cert_path, "ab") as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) log.debug("Certificate generated")
def cert(issuer, subject, pubkey, privkey, ca): builder = CertificateBuilder().issuer_name( Name([NameAttribute(NameOID.COMMON_NAME, issuer)]), ).subject_name( Name([NameAttribute(NameOID.COMMON_NAME, subject)]), ).add_extension( SubjectAlternativeName([DNSName(subject)]), critical=False, ) if ca: builder = builder.add_extension( BasicConstraints(True, None), critical=True, ) return builder.public_key( pubkey, ).serial_number(random_serial_number(), ).not_valid_before( datetime.utcnow(), ).not_valid_after( datetime.utcnow() + timedelta(seconds=1), ).sign( privkey, SHA256(), default_backend(), )
def self_signed_certificate(*hostname, **oid): """ Generates a self signed ssl_cert_key. Args: hostname (str): host name or IP address. oid (str): Object Identifiers. See "cryptography.x509.oid.NameOID" Returns: tuple of bytes: certificate and private key in PEM format. """ # Python 2: Unicode are required if version_info[0] == 2: oid = {key: unicode(value) for key, value in oid.items()} hostname = [unicode(value) for value in hostname] # Requester information name = Name([ NameAttribute(getattr(NameOID, key.upper()), value) for key, value in oid.items() ]) # IP addresses alternatives_names = [] for host in hostname: # DNS host name alternatives_names.append(DNSName(host)) # Host IP address try: alternatives_names.append(IPAddress(ip_address(host))) except ValueError: pass # Validity start date valid_from = datetime.utcnow() # Generates private RSA key private_key = generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) # Generates ssl_cert_key certificate = ( CertificateBuilder() # Requester information # Subject = Issuer on self signed certificates .subject_name(name).issuer_name(name) # Public key and serial number .public_key(private_key.public_key()).serial_number( random_serial_number()) # Validity .not_valid_before(valid_from).not_valid_after(valid_from + timedelta(days=VALIDITY)) # This ssl_cert_key can only sign itself .add_extension(BasicConstraints(ca=True, path_length=0), critical=False) # IP addresses .add_extension(SubjectAlternativeName(alternatives_names), critical=False) # Sign ssl_cert_key with private key .sign(private_key, SHA256(), default_backend())) # Generates public ssl_cert_key file certificate_bytes = certificate.public_bytes(encoding=Encoding.PEM) # Generates private key file private_key_bytes = private_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) return certificate_bytes, private_key_bytes