Best Python code snippet using autotest_python
container_reader.py
Source:container_reader.py  
1import binascii2import hashlib3import re as regex4from collections import OrderedDict5from enum import Enum6from oscrypto import keys as k7class ContainerTypes(Enum):8    Private = "Private"9    PKCS12 = "PKCS12"10    X509 = "X509"11    Undefined = None12class AbstractContainerReader(object):13    def __init__(self):14        self.bytes = None15        self.type = None16        self.password = None17        self.asn1 = None18        self._is_parsed = False19    @classmethod20    def by_bytes(cls, container_bytes, password=None):21        container = cls()22        container.bytes = container_bytes23        container.type = ContainerDetector.detect_type(container_bytes, password=password)24        container.password = password25        return container26    def is_parsed(self):27        return self._is_parsed28    def parse(self):29        '''30        Parses the bytes with a asn1 parser31        :return: None32        '''33        raise NotImplementedError()34    def der_dump(self):35        '''36        Dumpes the asn1 structure back to a uncrypted bytearray in DER format37        :return: bytearray38        '''39        raise NotImplementedError()40    def public_key_hash(self):41        '''42        Return a public key identifier. The identifier can be compared with others to find the43        private key/certificate pair44        :return: Identifier45        '''46        raise NotImplementedError()47    @classmethod48    def is_type(cls, container_bytes, password=None):49        '''50        Detects if the bytes have this ASN1 structure51        :return: Boolean52        '''53        raise NotImplementedError()54    def _sha256(self, value):55        '''56        Makes a sha256 hash over a string value. Formats the hash to be readable57        :param value: input58        :return: formated hash59        '''60        value = value.encode('utf-8')61        sha = hashlib.sha256()62        sha.update(value)63        hash_bytes = sha.digest()64        return self._format_hash(hash_bytes)65    def _format_hash(self, hash_bytes):66        hash_hex = binascii.hexlify(hash_bytes)67        hash_upper = hash_hex.decode('utf-8').upper()68        formated_hash = ""69        for part in regex.findall('..', hash_upper):70            formated_hash += part + ":"71        return formated_hash[:-1]72    def _raise_if_wrong_algorithm(self):73        algorithm_lower = self.algorithm().lower()74        wrong_algorihm = not (algorithm_lower == "rsa" or algorithm_lower == "ec")75        if wrong_algorihm:76            raise Exception("Detected unsupported algorithm " + str(algorithm_lower))77    def algorithm(self):78        '''79        :return: "rsa" or "ec"80        '''81        raise NotImplementedError()82class PrivateReader(AbstractContainerReader):83    @classmethod84    def is_type(cls, container_bytes, password=None):85        cert = None86        try:87            if password is None:88                cert = k.parse_private(container_bytes)89            else:90                cert = k.parse_private(container_bytes, password=password)91            cert.native92        except Exception:93            return False94        try:95            if cert.native["private_key"]["modulus"] is not None:96                return True97        except Exception:98            pass99        try:100            if cert.native["private_key"]["public_key"] is not None:101                return True102        except Exception:103            pass104        return False105    def parse(self):106        assert self.type == ContainerTypes.Private107        if self.password is None:108            self.asn1 = k.parse_private(self.bytes)109        else:110            self.asn1 = k.parse_private(self.bytes, password=self.password)111        self.asn1.native112        self._raise_if_wrong_algorithm()113        self._is_parsed = True114    def der_dump(self):115        return self.asn1.dump()116    def public_key_hash(self):117        if self.algorithm() == "rsa":118            ident = self.asn1.native["private_key"]["modulus"]119        elif self.algorithm() == "ec":120            ident = self.asn1.native["private_key"]["public_key"]121        return self._sha256(str(ident))122    def algorithm(self):123        return self.asn1.algorithm124class PKCS12Reader(AbstractContainerReader):125    @classmethod126    def is_type(cls, container_bytes, password=None):127        try:128            if password is None:129                k.parse_pkcs12(container_bytes)130            else:131                k.parse_pkcs12(container_bytes, password=password)132            return True133        except Exception:134            return False135    def parse(self):136        assert self.type == ContainerTypes.PKCS12137        if self.password is None:138            (self.privatekey, self.cert, self.certs) = k.parse_pkcs12(self.bytes)139        else:140            (self.privatekey, self.cert, self.certs) = k.parse_pkcs12(self.bytes, password=self.password)141        self._raise_if_wrong_algorithm()142        self._is_parsed = True143    def algorithm(self):144        return self.privatekey.algorithm145    def public_key_hash(self):146        if self.algorithm() == "rsa":147            ident = self.privatekey.native["private_key"]["modulus"]148        elif self.algorithm() == "ec":149            ident = self.privatekey.native["private_key"]["public_key"]150        return self._sha256(str(ident))151    def public_key(self):152        '''153        :return: the main X509 cert in this container154        :rtype X509Container155        '''156        data = self.cert.dump()157        container = X509Reader.by_bytes(data)158        container.parse()159        return container160    def private_key(self):161        '''162        :return: The private key in this container163        :rtype PrivateContainer164        '''165        data = self.privatekey.dump()166        container = PrivateReader.by_bytes(data)167        container.parse()168        return container169    def further_publics(self):170        '''171        :return: A list of X509 certs172        :rtype [X509Container]173        '''174        others = []175        for cer in self.certs:176            data = cer.dump()177            x509 = X509Reader.by_bytes(data)178            x509.parse()179            others.append(x509)180        return others181class X509Reader(AbstractContainerReader):182    @classmethod183    def is_type(cls, container_bytes, password=None):184        try:185            cert = k.parse_certificate(container_bytes)186            cert.native187            return True188        except Exception:189            return False190    def parse(self):191        assert self.type == ContainerTypes.X509192        self.asn1 = k.parse_certificate(self.bytes)193        self.asn1.native194        self._raise_if_wrong_algorithm()195        self._is_parsed = True196    def der_dump(self):197        return self.asn1.dump()198    def algorithm(self):199        return self.asn1.native["tbs_certificate"]["subject_public_key_info"]["algorithm"]["algorithm"]200    def public_key_hash(self):201        if self.algorithm() == "rsa":202            ident = self.asn1.native["tbs_certificate"]["subject_public_key_info"]["public_key"]["modulus"]203        elif self.algorithm() == "ec":204            ident = self.asn1.native["tbs_certificate"]["subject_public_key_info"]["public_key"]205        return self._sha256(str(ident))206    def is_cert_of(self, container):207        '''208        Compares the public keys of the container and this209        :param container: a private key container210        :type container: AbstractContainerReader211        :return: Boolean212        '''213        ident = container.public_key_hash()214        myident = self.public_key_hash()215        return ident == myident216    def serial_number(self):217        return self.asn1.serial_number218    def cname(self):219        return self.asn1.subject.native["common_name"]220class ContainerReaderException(Exception):221    pass222class ContainerDetector(object):223    _readers = OrderedDict([224        (ContainerTypes.X509, X509Reader),225        (ContainerTypes.PKCS12, PKCS12Reader),226        (ContainerTypes.Private, PrivateReader),227    ])228    @classmethod229    def detect_type(cls, container_bytes, password=None):230        '''231        Detects the type of an ASN.1 container232        :param container_bytes: bytes of the container in PEM or DER233        :param password: password of the container if encrypted234        :return: Type of the container235        :rtype ContainerTypes236        '''237        for ct, reader in cls._readers.items():238            if reader.is_type(container_bytes, password=password):239                return ct240        return ContainerTypes.Undefined241    @classmethod242    def factory(cls, container_bytes, password=None):243        '''244        Creates an instance of an ASN.1 container reader245        :param container_bytes: bytes of the container in PEM or DER246        :param password: password of the container if encrypted247        :return: container reader248        :rtype object derived of AbstractContainerReader249        '''250        reader = cls._readers[cls.detect_type(container_bytes, password)]251        if reader:252            return reader.by_bytes(container_bytes, password)...container.py
Source:container.py  
1from .utils.common_functions import to_int2class Container:3    def __init__(self,container_bytes: bytearray):4        self.container_bytes = container_bytes5        self.total_files = to_int(container_bytes[:4])6        self.idx_tbl_offset = to_int(container_bytes[4:8])7        self.load_files_table()8        self.load_files()9    10    def load_files_table(self):11        """12        Load the start offset for each file in the container13        """14        self.files_offset = []15        for i in range(self.total_files):16            offset = to_int(self.container_bytes[17                self.idx_tbl_offset + i * 4 : self.idx_tbl_offset + i * 4 + 418                ])19            self.files_offset.append(offset)20    def load_files(self):21        """22        Load each file into a list23        """24        self.files = []25        for i in range(self.total_files):26            if i == self.total_files -1:27                offset = bytearray(self.container_bytes[self.files_offset[i] : ])28            else:29                offset = bytearray(self.container_bytes[30                    self.files_offset[i] : self.files_offset[i + 1]31                    ])...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
