Python OpenSSL.crypto.FILETYPE_ASN1 Examples

The following are 30 code examples of OpenSSL.crypto.FILETYPE_ASN1(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module OpenSSL.crypto , or try the search function .
Example #1
Source File: _sslverify.py    From learn_python3_spider with MIT License 7 votes vote down vote up
def keyHash(self):
        """
        Compute a hash of the underlying PKey object.

        The purpose of this method is to allow you to determine if two
        certificates share the same public key; it is not really useful for
        anything else.

        In versions of Twisted prior to 15.0, C{keyHash} used a technique
        involving certificate requests for computing the hash that was not
        stable in the face of changes to the underlying OpenSSL library.

        @return: Return a 32-character hexadecimal string uniquely identifying
            this public key, I{for this version of Twisted}.
        @rtype: native L{str}
        """
        raw = crypto.dump_publickey(crypto.FILETYPE_ASN1, self.original)
        h = md5()
        h.update(raw)
        return h.hexdigest() 
Example #2
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_load_crl(self):
        """
        Load a known CRL and inspect its revocations.  Both EM and DER formats
        are loaded.
        """
        crl = load_crl(FILETYPE_PEM, crlData)
        revs = crl.get_revoked()
        assert len(revs) == 2
        assert revs[0].get_serial() == b'03AB'
        assert revs[0].get_reason() is None
        assert revs[1].get_serial() == b'0100'
        assert revs[1].get_reason() == b'Superseded'

        der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
        crl = load_crl(FILETYPE_ASN1, der)
        revs = crl.get_revoked()
        assert len(revs) == 2
        assert revs[0].get_serial() == b'03AB'
        assert revs[0].get_reason() is None
        assert revs[1].get_serial() == b'0100'
        assert revs[1].get_reason() == b'Superseded' 
Example #3
Source File: _sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def keyHash(self):
        """
        Compute a hash of the underlying PKey object.

        The purpose of this method is to allow you to determine if two
        certificates share the same public key; it is not really useful for
        anything else.

        In versions of Twisted prior to 15.0, C{keyHash} used a technique
        involving certificate requests for computing the hash that was not
        stable in the face of changes to the underlying OpenSSL library.

        @return: Return a 32-character hexadecimal string uniquely identifying
            this public key, I{for this version of Twisted}.
        @rtype: native L{str}
        """
        raw = crypto.dump_publickey(crypto.FILETYPE_ASN1, self.original)
        h = md5()
        h.update(raw)
        return h.hexdigest() 
Example #4
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_dump_certificate(self):
        """
        `dump_certificate` writes PEM, DER, and text.
        """
        pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
        cert = load_certificate(FILETYPE_PEM, pemData)
        dumped_pem = dump_certificate(FILETYPE_PEM, cert)
        assert dumped_pem == cleartextCertificatePEM
        dumped_der = dump_certificate(FILETYPE_ASN1, cert)
        good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
        assert dumped_der == good_der
        cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
        dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
        assert dumped_pem2 == cleartextCertificatePEM
        dumped_text = dump_certificate(FILETYPE_TEXT, cert)
        good_text = _runopenssl(
            dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
        assert dumped_text == good_text 
Example #5
Source File: publickey.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def pem_to_der_hex(self):
        """Convert PEM cert to DER format
        
        Converts PEM (Privacy Enhanced Mail) format to a hexadecimal 
        DER (Distinguished Encoding Rules) string.
        
        Returns:
            Chepy: The Chepy object.
        """
        cert_pem = _pyssl_crypto.load_certificate(
            _pyssl_crypto.FILETYPE_PEM, self.state
        )
        self.state = _pyssl_crypto.dump_certificate(
            _pyssl_crypto.FILETYPE_ASN1, cert_pem
        )
        return self 
Example #6
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_dump_certificate_request(self):
        """
        `dump_certificate_request` writes a PEM, DER, and text.
        """
        req = load_certificate_request(
            FILETYPE_PEM, cleartextCertificateRequestPEM)
        dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
        assert dumped_pem == cleartextCertificateRequestPEM
        dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
        good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
        assert dumped_der == good_der
        req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
        dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
        assert dumped_pem2 == cleartextCertificateRequestPEM
        dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
        good_text = _runopenssl(
            dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
        assert dumped_text == good_text
        with pytest.raises(ValueError):
            dump_certificate_request(100, req) 
Example #7
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_load_crl(self):
        """
        Load a known CRL and inspect its revocations.  Both
        PEM and DER formats are loaded.
        """
        crl = load_crl(FILETYPE_PEM, crlData)
        revs = crl.get_revoked()
        self.assertEqual(len(revs), 2)
        self.assertEqual(revs[0].get_serial(), b('03AB'))
        self.assertEqual(revs[0].get_reason(), None)
        self.assertEqual(revs[1].get_serial(), b('0100'))
        self.assertEqual(revs[1].get_reason(), b('Superseded'))

        der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
        crl = load_crl(FILETYPE_ASN1, der)
        revs = crl.get_revoked()
        self.assertEqual(len(revs), 2)
        self.assertEqual(revs[0].get_serial(), b('03AB'))
        self.assertEqual(revs[0].get_reason(), None)
        self.assertEqual(revs[1].get_serial(), b('0100'))
        self.assertEqual(revs[1].get_reason(), b('Superseded')) 
Example #8
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_export_text(self):
        """
        If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
        text format string like the one produced by the openssl command line
        tool.
        """
        crl = self._get_crl()

        dumped_crl = crl.export(self.cert, self.pkey, FILETYPE_ASN1)
        text = _runopenssl(
            dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
        )

        # text format
        dumped_text = crl.export(self.cert, self.pkey, type=FILETYPE_TEXT)
        self.assertEqual(text, dumped_text) 
Example #9
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_export_der(self):
        """
        If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
        "DER" format string representing a serial number, a revoked reason, and
        certificate issuer information.
        """
        crl = self._get_crl()

        # DER format
        dumped_crl = crl.export(self.cert, self.pkey, FILETYPE_ASN1)
        text = _runopenssl(
            dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
        )
        text.index(b('Serial Number: 03AB'))
        text.index(b('Superseded'))
        text.index(
            b('Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA')
        ) 
Example #10
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_dump_certificate_request(self):
        """
        :py:obj:`dump_certificate_request` writes a PEM, DER, and text.
        """
        req = load_certificate_request(FILETYPE_PEM, cleartextCertificateRequestPEM)
        dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
        self.assertEqual(dumped_pem, cleartextCertificateRequestPEM)
        dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
        good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
        self.assertEqual(dumped_der, good_der)
        req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
        dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
        self.assertEqual(dumped_pem2, cleartextCertificateRequestPEM)
        dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
        good_text = _runopenssl(dumped_pem, b"req", b"-noout", b"-text")
        self.assertEqual(dumped_text, good_text)
        self.assertRaises(ValueError, dump_certificate_request, 100, req) 
Example #11
Source File: publickey.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def parse_x509_der_hex(self):
        """Parse X509 cert in DER format
        
        X.509 is an ITU-T standard for a public key infrastructure (PKI) 
        and Privilege Management Infrastructure (PMI). It is commonly involved 
        with SSL/TLS security.<br><br>This operation displays the contents of 
        a certificate in a human readable format, similar to the openssl command line tool.
        
        Returns:
            Chepy: A Chepy object. 
        """
        cert = _pyssl_crypto.load_certificate(
            _pyssl_crypto.FILETYPE_ASN1, self._convert_to_bytes()
        )
        info = self._convert_cert_to_obj(cert)
        self.state = info
        return self 
Example #12
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_dump_certificate(self):
        """
        :py:obj:`dump_certificate` writes PEM, DER, and text.
        """
        pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
        cert = load_certificate(FILETYPE_PEM, pemData)
        dumped_pem = dump_certificate(FILETYPE_PEM, cert)
        self.assertEqual(dumped_pem, cleartextCertificatePEM)
        dumped_der = dump_certificate(FILETYPE_ASN1, cert)
        good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
        self.assertEqual(dumped_der, good_der)
        cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
        dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
        self.assertEqual(dumped_pem2, cleartextCertificatePEM)
        dumped_text = dump_certificate(FILETYPE_TEXT, cert)
        good_text = _runopenssl(dumped_pem, b"x509", b"-noout", b"-text")
        self.assertEqual(dumped_text, good_text) 
Example #13
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_export_der(self):
        """
        If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
        "DER" format string representing a serial number, a revoked reason, and
        certificate issuer information.
        """
        crl = self._get_crl()

        # DER format
        dumped_crl = self._get_crl().export(
            self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
        )
        crl = x509.load_der_x509_crl(dumped_crl, backend)
        revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
        assert revoked is not None
        assert crl.issuer == x509.Name([
            x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
            x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
            x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
            x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
            x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
        ])

    # Flaky because we compare the output of running commands which sometimes
    # varies by 1 second 
Example #14
Source File: ocsp_asn1crypto.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def extract_certificate_chain(self, connection):
        """Gets certificate chain and extract the key info from OpenSSL connection."""
        from OpenSSL.crypto import dump_certificate, FILETYPE_ASN1
        cert_map = OrderedDict()
        logger.debug(
            "# of certificates: %s",
            len(connection.get_peer_cert_chain()))

        for cert_openssl in connection.get_peer_cert_chain():
            cert_der = dump_certificate(FILETYPE_ASN1, cert_openssl)
            cert = Certificate.load(cert_der)
            logger.debug(
                'subject: %s, issuer: %s',
                cert.subject.native, cert.issuer.native)
            cert_map[cert.subject.sha256] = cert

        return self.create_pair_issuer_subject(cert_map) 
Example #15
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_load_privatekey_passphraseWrongType(self):
        """
        `load_privatekey` raises `ValueError` when it is passeda passphrase
        with a private key encoded in a format, that doesn't support
        encryption.
        """
        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
        blob = dump_privatekey(FILETYPE_ASN1, key)
        with pytest.raises(ValueError):
            load_privatekey(FILETYPE_ASN1, blob, "secret") 
Example #16
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_load_pkcs7_data_asn1(self):
        """
        `load_pkcs7_data` accepts a bytes containing ASN1 data representing
        PKCS#7 and returns an instance of `PKCS7`.
        """
        pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
        assert isinstance(pkcs7, PKCS7) 
Example #17
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_dump_privatekey_asn1(self):
        """
        `dump_privatekey` writes a DER
        """
        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
        dumped_pem = dump_privatekey(FILETYPE_PEM, key)

        dumped_der = dump_privatekey(FILETYPE_ASN1, key)
        # XXX This OpenSSL call writes "writing RSA key" to standard out.  Sad.
        good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
        assert dumped_der == good_der
        key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
        dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
        assert dumped_pem2 == cleartextPrivateKeyPEM 
Example #18
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_dump_privatekey_passphrase_wrong_type(self):
        """
        `dump_privatekey` raises `ValueError` when it is passed a passphrase
        with a private key encoded in a format, that doesn't support
        encryption.
        """
        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
        with pytest.raises(ValueError):
            dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret") 
Example #19
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_bad_file_type(self):
        """
        If the file type passed to `load_certificate_request` is neither
        `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
        """
        with pytest.raises(ValueError):
            load_certificate_request(object(), b"")
        with pytest.raises(ValueError):
            load_certificate(object(), b"") 
Example #20
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def signCertificateRequest(self,
                               requestData,
                               verifyDNCallback,
                               serialNumber,
                               requestFormat=crypto.FILETYPE_ASN1,
                               certificateFormat=crypto.FILETYPE_ASN1):
        issuer = self.getSubject()
        return self.privateKey.signCertificateRequest(
            issuer,
            requestData,
            verifyDNCallback,
            serialNumber,
            requestFormat,
            certificateFormat) 
Example #21
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def certificateRequest(self, format=crypto.FILETYPE_ASN1,
                           digestAlgorithm='md5'):
        return self.privateKey.certificateRequest(
            self.getSubject(),
            format,
            digestAlgorithm) 
Example #22
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
        """
        Create a new L{PrivateCertificate} from the given certificate data and
        this instance's private key.
        """
        return self.load(newCertData, self.privateKey, format) 
Example #23
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def dump(self, format=crypto.FILETYPE_ASN1):
        return crypto.dump_certificate_request(format, self.original) 
Example #24
Source File: _sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def certificateRequest(self, distinguishedName,
                           format=crypto.FILETYPE_ASN1,
                           digestAlgorithm='sha256'):
        """
        Create a certificate request signed with this key.

        @return: a string, formatted according to the 'format' argument.
        """
        return self.requestObject(distinguishedName, digestAlgorithm).dump(format) 
Example #25
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def load(Class, requestData, requestFormat=crypto.FILETYPE_ASN1):
        req = crypto.load_certificate_request(requestFormat, requestData)
        dn = DistinguishedName()
        dn._copyFrom(req.get_subject())
        if not req.verify(req.get_pubkey()):
            raise VerifyError("Can't verify that request for %r is self-signed." % (dn,))
        return Class(req) 
Example #26
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def dump(self, format=crypto.FILETYPE_ASN1):
        return crypto.dump_certificate(format, self.original) 
Example #27
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def load(Class, requestData, format=crypto.FILETYPE_ASN1, args=()):
        """
        Load a certificate from an ASN.1- or PEM-format string.

        @rtype: C{Class}
        """
        return Class(crypto.load_certificate(format, requestData), *args) 
Example #28
Source File: publickey.py    From chepy with GNU General Public License v3.0 5 votes vote down vote up
def der_hex_to_pem(self):
        """Convert DER format to PEM cert.
        
        Converts a hexadecimal DER (Distinguished Encoding Rules) 
        string into PEM (Privacy Enhanced Mail) format.
        
        Returns:
            Chepy: The Chepy object.

        Examples:
            >>> c = Chepy(str(Path().absolute() / "tests/files/test.der"))
            >>> c.load_file()
            >>> c.der_hex_to_pem()
            >>> c.o.decode()
            -----BEGIN CERTIFICATE-----
            MIICeTCCAeICCQDi5dgCpKMeHTANBgkqhkiG9w0BAQsFADCBgDELMAkGA1UEBhMC
            VVMxDDAKBgNVBAgMA2xvbDEMMAoGA1UEBwwDbnljMRIwEAYDVQQKDAlzZWN1cmlz
            ...
            wQSFm54UNQ/vjM12yZ+C5c3268Vo8jSP7mI5R3wn6XztjUSXkDg5/3IL3kojti/h
            nyhBHx2QCVke7BxWw3HWkbZ/1BKl0HnCGyd5HDTuOtlBmTS+QrJoNpdsn0zq4fvc
            igbV1IJdKTBAiZzaOQ==
            -----END CERTIFICATE-----
        """
        cert_pem = _pyssl_crypto.load_certificate(
            _pyssl_crypto.FILETYPE_ASN1, self._convert_to_bytes()
        )
        self.state = _pyssl_crypto.dump_certificate(
            _pyssl_crypto.FILETYPE_PEM, cert_pem
        )
        return self 
Example #29
Source File: _sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def signCertificateRequest(self,
                               requestData,
                               verifyDNCallback,
                               serialNumber,
                               requestFormat=crypto.FILETYPE_ASN1,
                               certificateFormat=crypto.FILETYPE_ASN1):
        issuer = self.getSubject()
        return self.privateKey.signCertificateRequest(
            issuer,
            requestData,
            verifyDNCallback,
            serialNumber,
            requestFormat,
            certificateFormat) 
Example #30
Source File: _sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def signCertificateRequest(self,
                               issuerDistinguishedName,
                               requestData,
                               verifyDNCallback,
                               serialNumber,
                               requestFormat=crypto.FILETYPE_ASN1,
                               certificateFormat=crypto.FILETYPE_ASN1,
                               secondsToExpiry=60 * 60 * 24 * 365, # One year
                               digestAlgorithm='sha256'):
        """
        Given a blob of certificate request data and a certificate authority's
        DistinguishedName, return a blob of signed certificate data.

        If verifyDNCallback returns a Deferred, I will return a Deferred which
        fires the data when that Deferred has completed.
        """
        hlreq = CertificateRequest.load(requestData, requestFormat)

        dn = hlreq.getSubject()
        vval = verifyDNCallback(dn)

        def verified(value):
            if not value:
                raise VerifyError("DN callback %r rejected request DN %r" % (verifyDNCallback, dn))
            return self.signRequestObject(issuerDistinguishedName, hlreq,
                                          serialNumber, secondsToExpiry, digestAlgorithm).dump(certificateFormat)

        if isinstance(vval, Deferred):
            return vval.addCallback(verified)
        else:
            return verified(vval)