How to use the cryptography.x509 function in cryptography

To help you get started, we’ve selected a few cryptography examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pyca / cryptography / tests / test_x509.py View on Github external
def test_subject_alt_names(self, backend):
        private_key = RSA_KEY_2048.private_key(backend)

        csr = x509.CertificateSigningRequestBuilder().subject_name(
            x509.Name([
                x509.NameAttribute(NameOID.COMMON_NAME, u"SAN"),
            ])
        ).add_extension(
            x509.SubjectAlternativeName([
                x509.DNSName(u"example.com"),
                x509.DNSName(u"*.example.com"),
                x509.RegisteredID(x509.ObjectIdentifier("1.2.3.4.5.6.7")),
                x509.DirectoryName(x509.Name([
                    x509.NameAttribute(NameOID.COMMON_NAME, u'PyCA'),
                    x509.NameAttribute(
                        NameOID.ORGANIZATION_NAME, u'We heart UTF8!\u2122'
                    )
                ])),
                x509.IPAddress(ipaddress.ip_address(u"127.0.0.1")),
                x509.IPAddress(ipaddress.ip_address(u"ff::")),
                x509.OtherName(
                    type_id=x509.ObjectIdentifier("1.2.3.3.3.3"),
                    value=b"0\x03\x02\x01\x05"
                ),
                x509.RFC822Name(u"test@example.com"),
                x509.RFC822Name(u"email"),
                x509.RFC822Name(u"email@em\xe5\xefl.com"),
                x509.UniformResourceIdentifier(
github trakt / Plex-Trakt-Scrobbler / Trakttv.bundle / Contents / Libraries / Linux / armv7_sf / marvell-pj4 / ucs4 / cryptography / hazmat / backends / openssl / x509.py View on Github external
"Duplicate {0} extension found".format(oid), oid
                )
            try:
                handler = self.handlers[oid]
            except KeyError:
                if critical:
                    raise x509.UnsupportedExtension(
                        "Critical extension {0} is not currently supported"
                        .format(oid), oid
                    )
                else:
                    # Dump the DER payload into an UnrecognizedExtension object
                    data = backend._lib.X509_EXTENSION_get_data(ext)
                    backend.openssl_assert(data != backend._ffi.NULL)
                    der = backend._ffi.buffer(data.data, data.length)[:]
                    unrecognized = x509.UnrecognizedExtension(oid, der)
                    extensions.append(
                        x509.Extension(oid, critical, unrecognized)
                    )
            else:
                # For extensions which are not supported by OpenSSL we pass the
                # extension object directly to the parsing routine so it can
                # be decoded manually.
                if self.unsupported_exts and oid in self.unsupported_exts:
                    ext_data = ext
                else:
                    ext_data = backend._lib.X509V3_EXT_d2i(ext)
                    if ext_data == backend._ffi.NULL:
                        backend._consume_errors()
                        raise ValueError(
                            "The {0} extension is invalid and can't be "
                            "parsed".format(oid)
github Avature / lxd-image-server / lxd_image_server / tools / cert.py View on Github external
def generate_cert(path):
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )

    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"lxd-image-server.localhost")])

    now = datetime.utcnow()
    basic_contraints = x509.BasicConstraints(ca=True, path_length=0)
    ip_address = get_address()
    cert = (
        x509.CertificateBuilder()
        .subject_name(name)
        .issuer_name(name)
        .public_key(key.public_key())
        .serial_number(1000)
        .not_valid_before(now - timedelta(days=10))
        .not_valid_after(now + timedelta(days=10 * 365))
        .add_extension(basic_contraints, False)
        .add_extension(
            x509.SubjectAlternativeName([
github sabnzbd / sabnzbd / sabnzbd / utils / certgen.py View on Github external
def generate_local_cert(private_key, days_valid=3560, output_file='cert.cert', LN=u'SABnzbd', ON=u'SABnzbd', CN=u'localhost'):
    # 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.LOCALITY_NAME, LN),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, ON),
        # x509.NameAttribute(NameOID.COMMON_NAME, CN),
    ])


    # build Subject Alternate Names (aka SAN) list
    # First the host names, add with x509.DNSName():
    san_list = [x509.DNSName(u"localhost")]
    san_list.append(x509.DNSName(unicode(socket.gethostname())))

    # Then the host IP addresses, add with x509.IPAddress()
    # Inside a try-except, just to be sure
    try:
        import ipaddress
        san_list.append(x509.IPAddress(ipaddress.IPv4Address(u"127.0.0.1")))
github tp4a / teleport / server / www / packages / packages-linux / x64 / cryptography / hazmat / backends / openssl / x509.py View on Github external
def signature_hash_algorithm(self):
        oid = self.signature_algorithm_oid
        try:
            return x509._SIG_OIDS_TO_HASH[oid]
        except KeyError:
            raise UnsupportedAlgorithm(
                "Signature algorithm OID:{0} not recognized".format(oid)
            )
github cloudera / hue / desktop / core / ext-py / cryptography-1.1.1 / src / cryptography / hazmat / backends / openssl / backend.py View on Github external
gn.d.registeredID = obj
    elif isinstance(name, x509.DirectoryName):
        gn = backend._lib.GENERAL_NAME_new()
        backend.openssl_assert(gn != backend._ffi.NULL)
        dir_name = _encode_name(backend, name.value)
        gn.type = backend._lib.GEN_DIRNAME
        gn.d.directoryName = dir_name
    elif isinstance(name, x509.IPAddress):
        gn = backend._lib.GENERAL_NAME_new()
        backend.openssl_assert(gn != backend._ffi.NULL)
        ipaddr = _encode_asn1_str(
            backend, name.value.packed, len(name.value.packed)
        )
        gn.type = backend._lib.GEN_IPADD
        gn.d.iPAddress = ipaddr
    elif isinstance(name, x509.OtherName):
        gn = backend._lib.GENERAL_NAME_new()
        backend.openssl_assert(gn != backend._ffi.NULL)
        other_name = backend._lib.OTHERNAME_new()
        backend.openssl_assert(other_name != backend._ffi.NULL)

        type_id = backend._lib.OBJ_txt2obj(
            name.type_id.dotted_string.encode('ascii'), 1
        )
        backend.openssl_assert(type_id != backend._ffi.NULL)
        data = backend._ffi.new("unsigned char[]", name.value)
        data_ptr_ptr = backend._ffi.new("unsigned char **")
        data_ptr_ptr[0] = data
        value = backend._lib.d2i_ASN1_TYPE(
            backend._ffi.NULL, data_ptr_ptr, len(name.value)
        )
        if value == backend._ffi.NULL:
github cloudera / hue / desktop / core / ext-py / cryptography-1.1.1 / src / cryptography / hazmat / backends / openssl / backend.py View on Github external
elif isinstance(name, x509.RegisteredID):
        gn = backend._lib.GENERAL_NAME_new()
        backend.openssl_assert(gn != backend._ffi.NULL)
        gn.type = backend._lib.GEN_RID
        obj = backend._lib.OBJ_txt2obj(
            name.value.dotted_string.encode('ascii'), 1
        )
        backend.openssl_assert(obj != backend._ffi.NULL)
        gn.d.registeredID = obj
    elif isinstance(name, x509.DirectoryName):
        gn = backend._lib.GENERAL_NAME_new()
        backend.openssl_assert(gn != backend._ffi.NULL)
        dir_name = _encode_name(backend, name.value)
        gn.type = backend._lib.GEN_DIRNAME
        gn.d.directoryName = dir_name
    elif isinstance(name, x509.IPAddress):
        gn = backend._lib.GENERAL_NAME_new()
        backend.openssl_assert(gn != backend._ffi.NULL)
        ipaddr = _encode_asn1_str(
            backend, name.value.packed, len(name.value.packed)
        )
        gn.type = backend._lib.GEN_IPADD
        gn.d.iPAddress = ipaddr
    elif isinstance(name, x509.OtherName):
        gn = backend._lib.GENERAL_NAME_new()
        backend.openssl_assert(gn != backend._ffi.NULL)
        other_name = backend._lib.OTHERNAME_new()
        backend.openssl_assert(other_name != backend._ffi.NULL)

        type_id = backend._lib.OBJ_txt2obj(
            name.type_id.dotted_string.encode('ascii'), 1
        )
github AppScale / appscale / APIServer / appscale / api_server / crypto.py View on Github external
Returns:
            A PublicCertificate.
        """
        try:
            cert_details = json.loads(cert_data)
        except ValueError:
            raise InvalidCertificate('Invalid JSON')

        try:
            key_name = cert_details['key_name']
            pem = cert_details['pem'].encode('utf-8')
        except KeyError as error:
            raise InvalidCertificate(str(error))

        try:
            cert = x509.load_pem_x509_certificate(pem, default_backend())
        except ValueError as error:
            raise InvalidCertificate(str(error))

        return cls(key_name, cert, node_name)
github Netflix / lemur / lemur / plugins / lemur_cryptography / plugin.py View on Github external
def issue_certificate(csr, options, private_key=None):
    csr = x509.load_pem_x509_csr(csr.encode("utf-8"), default_backend())

    if options.get("parent"):
        # creating intermediate authorities will have options['parent'] to specify the issuer
        # creating certificates will have options['authority'] to specify the issuer
        # This works around that by making sure options['authority'] can be referenced for either
        options["authority"] = options["parent"]

    if options.get("authority"):
        # Issue certificate signed by an existing lemur_certificates authority
        issuer_subject = options["authority"].authority_certificate.subject
        assert (
            private_key is None
        ), "Private would be ignored, authority key used instead"
        private_key = options["authority"].authority_certificate.private_key
        chain_cert_pem = options["authority"].authority_certificate.body
        authority_key_identifier_public = options[
github WoTTsecurity / agent / agent / src / agent / main.py View on Github external
def generate_cert(device_id):
    private_key = ec.generate_private_key(
        ec.SECP384R1(), default_backend()
    )
    builder = x509.CertificateSigningRequestBuilder()

    builder = builder.subject_name(x509.Name([
                x509.NameAttribute(NameOID.COMMON_NAME, u'{}'.format(device_id)),
                x509.NameAttribute(NameOID.COUNTRY_NAME, u'UK'),
                x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'London'),
                x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Web of Trusted Things'),
            ]))

    builder = builder.add_extension(
        x509.SubjectAlternativeName(
            [x509.DNSName(u'{}'.format(device_id))]
        ),
        critical=False
    )

    csr = builder.sign(private_key, hashes.SHA256(), default_backend())

    serialized_private_key = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
    serialized_csr = csr.public_bytes(serialization.Encoding.PEM)

    return {
        'csr': serialized_csr.decode(),