How to use the asn1crypto.cms.ContentInfo.load function in asn1crypto

To help you get started, we’ve selected a few asn1crypto 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 wbond / asn1crypto / tests / test_cms.py View on Github external
def test_parse_content_info_pkcs7_signed_data(self):
        with open(os.path.join(fixtures_dir, 'pkcs7-signed.der'), 'rb') as f:
            info = cms.ContentInfo.load(f.read())

        signed_data = info['content']
        encap_content_info = signed_data['encap_content_info']

        self.assertEqual(
            'signed_data',
            info['content_type'].native
        )
        self.assertEqual(
            'v1',
            signed_data['version'].native
        )
        self.assertEqual(
            [
                util.OrderedDict([
                    ('algorithm', 'sha256'),
github wbond / asn1crypto / tests / test_cms.py View on Github external
def test_parse_content_info_pkcs7_signed_digested_data(self):
        with open(os.path.join(fixtures_dir, 'pkcs7-signed-digested.der'), 'rb') as f:
            info = cms.ContentInfo.load(f.read())

        signed_data = info['content']
        encap_content_info = signed_data['encap_content_info']

        self.assertEqual(
            'signed_data',
            info['content_type'].native
        )
        self.assertEqual(
            'v1',
            signed_data['version'].native
        )
        self.assertEqual(
            [
                util.OrderedDict([
                    ('algorithm', 'sha256'),
github androguard / androguard / androguard / core / bytecodes / apk.py View on Github external
def get_certificate_der(self, filename):
        """
        Return the DER coded X.509 certificate from the signature file.

        :param filename: Signature filename in APK
        :returns: DER coded X.509 certificate as binary
        """
        pkcs7message = self.get_file(filename)

        pkcs7obj = cms.ContentInfo.load(pkcs7message)
        cert = pkcs7obj['content']['certificates'][0].chosen.dump()
        return cert
github cmdmnt / commandment / scep / message.py View on Github external
def parse(cls, raw: bytes):
        msg = cls()

        cinfo = ContentInfo.load(raw)
        assert cinfo['content_type'].native == 'signed_data'
        signed_data = cinfo['content']

        # convert certificates using cryptography lib since it is easier to deal with the decryption
        assert len(signed_data['certificates']) > 0
        certs = certificates_from_asn1(signed_data['certificates'])
        print('{} certificate(s) attached to signedData'.format(len(certs)))
        msg._certificates = certs
        
        # Iterate through signers and verify the signature for each.
        # Set convenience attributes at the same time
        for signer_info in cinfo['content']['signer_infos']:
            # version can be 1 (issuerandserial) or 3 (subjectkeyidentifier)
            # assert signer_info['version'] == 1
            identifier = signer_info['sid'].chosen
            assert isinstance(identifier, IssuerAndSerialNumber)  # TODO: also support other signer ids
github aaronst / macholibre / macholibre / parser.py View on Github external
if magic != dictionary.signatures['BLOBWRAPPER']:
            self.add_abnormality('Bad magic "{}" for certificate blob wrapper '
                                 'at offset "{}".'.format(magic, true_offset))

            return []

        # subtract 8 to ignore magic and size fields
        size = self.get_int(ignore_endian=True) - 8

        if size <= 0:
            self.add_abnormality('Non-positive CMS size "{}" at offset '
                                 '"{}".'.format(size, self.__file.tell() - 4))

            return []

        signed_data = ContentInfo.load(self.__file.read(size))['content']

        self.__macho['code_signature']['certs'] = []

        for cert in signed_data['certificates']:
            cert = cert.chosen

            if self.__extract_certs:
                c_bytes = cert.dump()
                open(hashlib.md5(c_bytes).hexdigest(), 'wb').write(c_bytes)

            subject = {}

            for rdn in cert.subject.chosen:
                name = rdn[0]['type'].human_friendly
                value = rdn[0]['value']
github cmdmnt / commandment / commandment / cms / decorators.py View on Github external
def _verify_cms_signers(signed_data: bytes, detached: bool = False) -> Tuple[List[x509.Certificate], bytes]:
    ci = cms.ContentInfo.load(signed_data)
    assert ci['content_type'].native == 'signed_data'
    signed: cms.SignedData = ci['content']

    current_app.logger.debug("CMS request contains %d certificate(s)", len(signed['certificates']))

    signers = []
    for signer in signed['signer_infos']:
        asn_certificate = _certificate_by_signer_identifier(signed['certificates'], signer['sid'])
        assert asn_certificate is not None
        certificate = x509.load_der_x509_certificate(asn_certificate.dump(), default_backend())

        digest_algorithm = signer['digest_algorithm']
        signature_algorithm = signer['signature_algorithm']

        hash_function = _cryptography_hash_function(digest_algorithm)
        pad_function = _cryptography_pad_function(signature_algorithm)
github laurivosandi / certidude / certidude / api / scep.py View on Github external
# Verify signature
            try:
                asymmetric.rsa_pkcs1v15_verify(
                    asymmetric.load_certificate(current_certificate.dump()),
                    signer["signature"].native,
                    b"\x31" + msg[1:], # wtf?!
                    "md5")
            except SignatureError:
                raise SCEPSignatureMismatch()


            ###############################
            ### Decrypt inner container ###
            ###############################

            info = cms.ContentInfo.load(encap_content.native)
            encrypted_envelope = info['content']
            encrypted_content_info = encrypted_envelope['encrypted_content_info']
            iv = encrypted_content_info['content_encryption_algorithm']['parameters'].native

            if encrypted_content_info['content_encryption_algorithm']["algorithm"].native != "des":
                raise SCEPBadAlgo()

            encrypted_content = encrypted_content_info['encrypted_content'].native
            recipient, = encrypted_envelope['recipient_infos']

            if recipient.native["rid"]["serial_number"] != self.authority.certificate.serial_number:
                raise SCEPBadCertId()

            key = asymmetric.rsa_pkcs1v15_decrypt(
                self.authority.private_key,
                recipient.native["encrypted_key"])
github cmdmnt / commandment / scep / message.py View on Github external
def encap_content_info(self) -> ContentInfo:
        return ContentInfo.load(self._signed_data.native)
github laurivosandi / certidude / certidude / api / scep.py View on Github external
# If we bump into exceptions later
        encrypted_container = b""
        attr_list = [
            cms.CMSAttribute({
                'type': "message_type",
                'values': ["3"]
            }),
            cms.CMSAttribute({
                'type': "pki_status",
                'values': ["2"] # rejected
            })
        ]

        try:
            info = cms.ContentInfo.load(b64decode(req.get_param("message", required=True)))

            ###############################################
            ### Verify signature of the outer container ###
            ###############################################

            signed_envelope = info['content']
            encap_content_info = signed_envelope['encap_content_info']
            encap_content = encap_content_info['content']

            # TODO: try except
            current_certificate, = signed_envelope["certificates"]
            signer, = signed_envelope["signer_infos"]

            # TODO: compare cert to current one if we are renewing

            digest_algorithm = signer["digest_algorithm"]["algorithm"].native