def unwrap(string, *params):
    """
    Takes a multi-line string and does the following:

     - dedents
     - converts newlines with text before and after into a single line
     - strips leading and trailing whitespace

    :param string:
        The string to format

    :param *params:
        Params to interpolate into the string

    :return:
        The formatted string
    """

    output = textwrap.dedent(string)

    # Unwrap lines, taking into account bulleted lists, ordered lists and
    # underlines consisting of = signs
    if output.find('\n') != -1:
        output = re.sub('(?<=\\S)\n(?=[^ \n\t\\d\\*\\-=])', ' ', output)

    if params:
        output = output % params

    output = output.strip()

    return output def iri_to_uri(value, normalize=False):
    """
    Encodes a unicode IRI into an ASCII byte string URI

    :param value:
        A unicode string of an IRI

    :param normalize:
        A bool that controls URI normalization

    :return:
        A byte string of the ASCII-encoded URI
    """

    if not isinstance(value, str_cls):
        raise TypeError(unwrap(
            '''
            value must be a unicode string, not %s
            ''',
            type_name(value)
        ))

    scheme = None
    # Python 2.6 doesn't split properly is the URL doesn't start with http:// or https://
    if sys.version_info < (2, 7) and not value.startswith('http://') and not value.startswith('https://'):
        real_prefix = None
        prefix_match = re.match('^[^:]*://', value)
        if prefix_match:
            real_prefix = prefix_match.group(0)
            value = 'http://' + value[len(real_prefix):]
        parsed = urlsplit(value)
        if real_prefix:
            value = real_prefix + value[7:]
            scheme = _urlquote(real_prefix[:-3])
    else:
        parsed = urlsplit(value)

    if scheme is None:
        scheme = _urlquote(parsed.scheme)
    hostname = parsed.hostname
    if hostname is not None:
        hostname = hostname.encode('idna')
    # RFC 3986 allows userinfo to contain sub-delims
    username = _urlquote(parsed.username, safe='!$&\'()*+,;=')
    password = _urlquote(parsed.password, safe='!$&\'()*+,;=')
    port = parsed.port
    if port is not None:
        port = str_cls(port).encode('ascii')

    netloc = b''
    if username is not None:
        netloc += username
        if password:
            netloc += b':' + password
        netloc += b'@'
    if hostname is not None:
        netloc += hostname
    if port is not None:
        default_http = scheme == b'http' and port == b'80'
        default_https = scheme == b'https' and port == b'443'
        if not normalize or (not default_http and not default_https):
            netloc += b':' + port

    # RFC 3986 allows a path to contain sub-delims, plus "@" and ":"
    path = _urlquote(parsed.path, safe='/!$&\'()*+,;=@:')
    # RFC 3986 allows the query to contain sub-delims, plus "@", ":" , "/" and "?"
    query = _urlquote(parsed.query, safe='/?!$&\'()*+,;=@:')
    # RFC 3986 allows the fragment to contain sub-delims, plus "@", ":" , "/" and "?"
    fragment = _urlquote(parsed.fragment, safe='/?!$&\'()*+,;=@:')

    if normalize and query is None and fragment is None and path == b'/':
        path = None

    # Python 2.7 compat
    if path is None:
        path = ''

    output = urlunsplit((scheme, netloc, path, query, fragment))
    if isinstance(output, str_cls):
        output = output.encode('latin1')
    return output def uri_to_iri(value):
    """
    Converts an ASCII URI byte string into a unicode IRI

    :param value:
        An ASCII-encoded byte string of the URI

    :return:
        A unicode string of the IRI
    """

    if not isinstance(value, byte_cls):
        raise TypeError(unwrap(
            '''
            value must be a byte string, not %s
            ''',
            type_name(value)
        ))

    parsed = urlsplit(value)

    scheme = parsed.scheme
    if scheme is not None:
        scheme = scheme.decode('ascii')

    username = _urlunquote(parsed.username, remap=[':', '@'])
    password = _urlunquote(parsed.password, remap=[':', '@'])
    hostname = parsed.hostname
    if hostname:
        hostname = hostname.decode('idna')
    port = parsed.port
    if port and not isinstance(port, int_types):
        port = port.decode('ascii')

    netloc = ''
    if username is not None:
        netloc += username
        if password:
            netloc += ':' + password
        netloc += '@'
    if hostname is not None:
        netloc += hostname
    if port is not None:
        netloc += ':' + str_cls(port)

    path = _urlunquote(parsed.path, remap=['/'], preserve=True)
    query = _urlunquote(parsed.query, remap=['&', '='], preserve=True)
    fragment = _urlunquote(parsed.fragment)

    return urlunsplit((scheme, netloc, path, query, fragment)) class AlgorithmIdentifier(Sequence):
    _fields = [
        ('algorithm', ObjectIdentifier),
        ('parameters', Any, {'optional': True}),
    ] class AnyAlgorithmIdentifier(_ForceNullParameters, Sequence):
    _fields = [
        ('algorithm', AnyAlgorithmId),
        ('parameters', Any, {'optional': True}),
    ]

    _oid_pair = ('algorithm', 'parameters')
    _oid_specs = {}

    def _setup(self):
        Sequence._setup(self)
        specs = self.__class__._oid_specs
        for other_cls in (EncryptionAlgorithm, SignedDigestAlgorithm):
            for oid, spec in other_cls._oid_specs.items():
                specs[oid] = spec class DigestAlgorithm(_ForceNullParameters, Sequence):
    _fields = [
        ('algorithm', DigestAlgorithmId),
        ('parameters', Any, {'optional': True}),
    ] class SignedDigestAlgorithm(_ForceNullParameters, Sequence):
    _fields = [
        ('algorithm', SignedDigestAlgorithmId),
        ('parameters', Any, {'optional': True}),
    ]

    _oid_pair = ('algorithm', 'parameters')
    _oid_specs = {
        'rsassa_pss': RSASSAPSSParams,
    }

    @property
    def signature_algo(self):
        """
        :return:
            A unicode string of "rsassa_pkcs1v15", "rsassa_pss", "dsa",
            "ecdsa", "ed25519" or "ed448"
        """

        algorithm = self['algorithm'].native

        algo_map = {
            'md2_rsa': 'rsassa_pkcs1v15',
            'md5_rsa': 'rsassa_pkcs1v15',
            'sha1_rsa': 'rsassa_pkcs1v15',
            'sha224_rsa': 'rsassa_pkcs1v15',
            'sha256_rsa': 'rsassa_pkcs1v15',
            'sha384_rsa': 'rsassa_pkcs1v15',
            'sha512_rsa': 'rsassa_pkcs1v15',
            'rsassa_pkcs1v15': 'rsassa_pkcs1v15',
            'rsassa_pss': 'rsassa_pss',
            'sha1_dsa': 'dsa',
            'sha224_dsa': 'dsa',
            'sha256_dsa': 'dsa',
            'dsa': 'dsa',
            'sha1_ecdsa': 'ecdsa',
            'sha224_ecdsa': 'ecdsa',
            'sha256_ecdsa': 'ecdsa',
            'sha384_ecdsa': 'ecdsa',
            'sha512_ecdsa': 'ecdsa',
            'sha3_224_ecdsa': 'ecdsa',
            'sha3_256_ecdsa': 'ecdsa',
            'sha3_384_ecdsa': 'ecdsa',
            'sha3_512_ecdsa': 'ecdsa',
            'ecdsa': 'ecdsa',
            'ed25519': 'ed25519',
            'ed448': 'ed448',
        }
        if algorithm in algo_map:
            return algo_map[algorithm]

        raise ValueError(unwrap(
            '''
            Signature algorithm not known for %s
            ''',
            algorithm
        ))

    @property
    def hash_algo(self):
        """
        :return:
            A unicode string of "md2", "md5", "sha1", "sha224", "sha256",
            "sha384", "sha512", "sha512_224", "sha512_256" or "shake256"
        """

        algorithm = self['algorithm'].native

        algo_map = {
            'md2_rsa': 'md2',
            'md5_rsa': 'md5',
            'sha1_rsa': 'sha1',
            'sha224_rsa': 'sha224',
            'sha256_rsa': 'sha256',
            'sha384_rsa': 'sha384',
            'sha512_rsa': 'sha512',
            'sha1_dsa': 'sha1',
            'sha224_dsa': 'sha224',
            'sha256_dsa': 'sha256',
            'sha1_ecdsa': 'sha1',
            'sha224_ecdsa': 'sha224',
            'sha256_ecdsa': 'sha256',
            'sha384_ecdsa': 'sha384',
            'sha512_ecdsa': 'sha512',
            'ed25519': 'sha512',
            'ed448': 'shake256',
        }
        if algorithm in algo_map:
            return algo_map[algorithm]

        if algorithm == 'rsassa_pss':
            return self['parameters']['hash_algorithm']['algorithm'].native

        raise ValueError(unwrap(
            '''
            Hash algorithm not known for %s
            ''',
            algorithm
        )) class Any(Asn1Value):
    """
    A value class that can contain any value, and allows for easy parsing of
    the underlying encoded value using a spec. This is normally contained in
    a Structure that has an ObjectIdentifier field and _oid_pair and _oid_specs
    defined.
    """

    # The parsed value object
    _parsed = None

    def __init__(self, value=None, **kwargs):
        """
        Sets the value of the object before passing to Asn1Value.__init__()

        :param value:
            An Asn1Value object that will be set as the parsed value
        """

        Asn1Value.__init__(self, **kwargs)

        try:
            if value is not None:
                if not isinstance(value, Asn1Value):
                    raise TypeError(unwrap(
                        '''
                        value must be an instance of Asn1Value, not %s
                        ''',
                        type_name(value)
                    ))

                self._parsed = (value, value.__class__, None)
                self.contents = value.dump()

        except (ValueError, TypeError) as e:
            args = e.args[1:]
            e.args = (e.args[0] + '\n    while constructing %s' % type_name(self),) + args
            raise e

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            The .native value from the parsed value object
        """

        if self._parsed is None:
            self.parse()

        return self._parsed[0].native

    @property
    def parsed(self):
        """
        Returns the parsed object from .parse()

        :return:
            The object returned by .parse()
        """

        if self._parsed is None:
            self.parse()

        return self._parsed[0]

    def parse(self, spec=None, spec_params=None):
        """
        Parses the contents generically, or using a spec with optional params

        :param spec:
            A class derived from Asn1Value that defines what class_ and tag the
            value should have, and the semantics of the encoded value. The
            return value will be of this type. If omitted, the encoded value
            will be decoded using the standard universal tag based on the
            encoded tag number.

        :param spec_params:
            A dict of params to pass to the spec object

        :return:
            An object of the type spec, or if not present, a child of Asn1Value
        """

        if self._parsed is None or self._parsed[1:3] != (spec, spec_params):
            try:
                passed_params = spec_params or {}
                _tag_type_to_explicit_implicit(passed_params)
                if self.explicit is not None:
                    if 'explicit' in passed_params:
                        passed_params['explicit'] = self.explicit + passed_params['explicit']
                    else:
                        passed_params['explicit'] = self.explicit
                contents = self._header + self.contents + self._trailer
                parsed_value, _ = _parse_build(
                    contents,
                    spec=spec,
                    spec_params=passed_params
                )
                self._parsed = (parsed_value, spec, spec_params)

                # Once we've parsed the Any value, clear any attributes from this object
                # since they are now duplicate
                self.tag = None
                self.explicit = None
                self.implicit = False
                self._header = b''
                self.contents = contents
                self._trailer = b''

            except (ValueError, TypeError) as e:
                args = e.args[1:]
                e.args = (e.args[0] + '\n    while parsing %s' % type_name(self),) + args
                raise e
        return self._parsed[0]

    def _copy(self, other, copy_func):
        """
        Copies the contents of another Any object to itself

        :param object:
            Another instance of the same class

        :param copy_func:
            An reference of copy.copy() or copy.deepcopy() to use when copying
            lists, dicts and objects
        """

        super(Any, self)._copy(other, copy_func)
        self._parsed = copy_func(other._parsed)

    def dump(self, force=False):
        """
        Encodes the value using DER

        :param force:
            If the encoded contents already exist, clear them and regenerate
            to ensure they are in DER format instead of BER format

        :return:
            A byte string of the DER-encoded value
        """

        if self._parsed is None:
            self.parse()

        return self._parsed[0].dump(force=force) class BitString(_IntegerBitString, Constructable, Castable, Primitive, ValueMap):
    """
    Represents a bit string from ASN.1 as a Python tuple of 1s and 0s
    """

    tag = 3

    _size = None

    def _setup(self):
        """
        Generates _reverse_map from _map
        """

        ValueMap._setup(self)

        cls = self.__class__
        if cls._map is not None:
            cls._size = max(self._map.keys()) + 1

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            An integer or a tuple of integers 0 and 1

        :raises:
            ValueError - when an invalid value is passed
        """

        if isinstance(value, set):
            if self._map is None:
                raise ValueError(unwrap(
                    '''
                    %s._map has not been defined
                    ''',
                    type_name(self)
                ))

            bits = [0] * self._size
            self._native = value
            for index in range(0, self._size):
                key = self._map.get(index)
                if key is None:
                    continue
                if key in value:
                    bits[index] = 1

            value = ''.join(map(str_cls, bits))

        elif value.__class__ == tuple:
            if self._map is None:
                self._native = value
            else:
                self._native = set()
                for index, bit in enumerate(value):
                    if bit:
                        name = self._map.get(index, index)
                        self._native.add(name)
            value = ''.join(map(str_cls, value))

        else:
            raise TypeError(unwrap(
                '''
                %s value must be a tuple of ones and zeros or a set of unicode
                strings, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        if self._map is not None:
            if len(value) > self._size:
                raise ValueError(unwrap(
                    '''
                    %s value must be at most %s bits long, specified was %s long
                    ''',
                    type_name(self),
                    self._size,
                    len(value)
                ))
            # A NamedBitList must have trailing zero bit truncated. See
            # https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
            # section 11.2,
            # https://tools.ietf.org/html/rfc5280#page-134 and
            # https://www.ietf.org/mail-archive/web/pkix/current/msg10443.html
            value = value.rstrip('0')
        size = len(value)

        size_mod = size % 8
        extra_bits = 0
        if size_mod != 0:
            extra_bits = 8 - size_mod
            value += '0' * extra_bits

        size_in_bytes = int(math.ceil(size / 8))

        if extra_bits:
            extra_bits_byte = int_to_bytes(extra_bits)
        else:
            extra_bits_byte = b'\x00'

        if value == '':
            value_bytes = b''
        else:
            value_bytes = int_to_bytes(int(value, 2))
        if len(value_bytes) != size_in_bytes:
            value_bytes = (b'\x00' * (size_in_bytes - len(value_bytes))) + value_bytes

        self.contents = extra_bits_byte + value_bytes
        self._unused_bits = (0,) * extra_bits
        self._header = None
        if self._indefinite:
            self._indefinite = False
            self.method = 0
        if self._trailer != b'':
            self._trailer = b''

    def __getitem__(self, key):
        """
        Retrieves a boolean version of one of the bits based on a name from the
        _map

        :param key:
            The unicode string of one of the bit names

        :raises:
            ValueError - when _map is not set or the key name is invalid

        :return:
            A boolean if the bit is set
        """

        is_int = isinstance(key, int_types)
        if not is_int:
            if not isinstance(self._map, dict):
                raise ValueError(unwrap(
                    '''
                    %s._map has not been defined
                    ''',
                    type_name(self)
                ))

            if key not in self._reverse_map:
                raise ValueError(unwrap(
                    '''
                    %s._map does not contain an entry for "%s"
                    ''',
                    type_name(self),
                    key
                ))

        if self._native is None:
            self.native

        if self._map is None:
            if len(self._native) >= key + 1:
                return bool(self._native[key])
            return False

        if is_int:
            key = self._map.get(key, key)

        return key in self._native

    def __setitem__(self, key, value):
        """
        Sets one of the bits based on a name from the _map

        :param key:
            The unicode string of one of the bit names

        :param value:
            A boolean value

        :raises:
            ValueError - when _map is not set or the key name is invalid
        """

        is_int = isinstance(key, int_types)
        if not is_int:
            if self._map is None:
                raise ValueError(unwrap(
                    '''
                    %s._map has not been defined
                    ''',
                    type_name(self)
                ))

            if key not in self._reverse_map:
                raise ValueError(unwrap(
                    '''
                    %s._map does not contain an entry for "%s"
                    ''',
                    type_name(self),
                    key
                ))

        if self._native is None:
            self.native

        if self._map is None:
            new_native = list(self._native)
            max_key = len(new_native) - 1
            if key > max_key:
                new_native.extend([0] * (key - max_key))
            new_native[key] = 1 if value else 0
            self._native = tuple(new_native)

        else:
            if is_int:
                key = self._map.get(key, key)

            if value:
                if key not in self._native:
                    self._native.add(key)
            else:
                if key in self._native:
                    self._native.remove(key)

        self.set(self._native)

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            If a _map is set, a set of names, or if no _map is set, a tuple of
            integers 1 and 0. None if no value.
        """

        # For BitString we default the value to be all zeros
        if self.contents is None:
            if self._map is None:
                self.set(())
            else:
                self.set(set())

        if self._native is None:
            int_value, bit_count, self._unused_bits = self._chunks_to_int()
            bits = _int_to_bit_tuple(int_value, bit_count)

            if self._map:
                self._native = set()
                for index, bit in enumerate(bits):
                    if bit:
                        name = self._map.get(index, index)
                        self._native.add(name)
            else:
                self._native = bits
        return self._native class BMPString(AbstractString):
    """
    Represents a BMP string from ASN.1 as a Python unicode string
    """

    tag = 30
    _encoding = 'utf-16-be' class Boolean(Primitive):
    """
    Represents a boolean in both ASN.1 and Python
    """

    tag = 1

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            True, False or another value that works with bool()
        """

        self._native = bool(value)
        self.contents = b'\x00' if not value else b'\xff'
        self._header = None
        if self._trailer != b'':
            self._trailer = b''

    # Python 2
    def __nonzero__(self):
        """
        :return:
            True or False
        """
        return self.__bool__()

    def __bool__(self):
        """
        :return:
            True or False
        """
        return self.contents != b'\x00'

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            True, False or None
        """

        if self.contents is None:
            return None

        if self._native is None:
            self._native = self.__bool__()
        return self._native class Choice(Asn1Value):
    """
    A class to handle when a value may be one of several options
    """

    # The index in _alternatives of the validated alternative
    _choice = None

    # The name of the chosen alternative
    _name = None

    # The Asn1Value object for the chosen alternative
    _parsed = None

    # Choice overrides .contents to be a property so that the code expecting
    # the .contents attribute will get the .contents of the chosen alternative
    _contents = None

    # A list of tuples in one of the following forms.
    #
    # Option 1, a unicode string field name and a value class
    #
    # ("name", Asn1ValueClass)
    #
    # Option 2, same as Option 1, but with a dict of class params
    #
    # ("name", Asn1ValueClass, {'explicit': 5})
    _alternatives = None

    # A dict that maps tuples of (class_, tag) to an index in _alternatives
    _id_map = None

    # A dict that maps alternative names to an index in _alternatives
    _name_map = None

    @classmethod
    def load(cls, encoded_data, strict=False, **kwargs):
        """
        Loads a BER/DER-encoded byte string using the current class as the spec

        :param encoded_data:
            A byte string of BER or DER encoded data

        :param strict:
            A boolean indicating if trailing data should be forbidden - if so, a
            ValueError will be raised when trailing data exists

        :return:
            A instance of the current class
        """

        if not isinstance(encoded_data, byte_cls):
            raise TypeError('encoded_data must be a byte string, not %s' % type_name(encoded_data))

        value, _ = _parse_build(encoded_data, spec=cls, spec_params=kwargs, strict=strict)
        return value

    def _setup(self):
        """
        Generates _id_map from _alternatives to allow validating contents
        """

        cls = self.__class__
        cls._id_map = {}
        cls._name_map = {}
        for index, info in enumerate(cls._alternatives):
            if len(info) < 3:
                info = info + ({},)
                cls._alternatives[index] = info
            id_ = _build_id_tuple(info[2], info[1])
            cls._id_map[id_] = index
            cls._name_map[info[0]] = index

    def __init__(self, name=None, value=None, **kwargs):
        """
        Checks to ensure implicit tagging is not being used since it is
        incompatible with Choice, then forwards on to Asn1Value.__init__()

        :param name:
            The name of the alternative to be set - used with value.
            Alternatively this may be a dict with a single key being the name
            and the value being the value, or a two-element tuple of the name
            and the value.

        :param value:
            The alternative value to set - used with name

        :raises:
            ValueError - when implicit param is passed (or legacy tag_type param is "implicit")
        """

        _tag_type_to_explicit_implicit(kwargs)

        Asn1Value.__init__(self, **kwargs)

        try:
            if kwargs.get('implicit') is not None:
                raise ValueError(unwrap(
                    '''
                    The Choice type can not be implicitly tagged even if in an
                    implicit module - due to its nature any tagging must be
                    explicit
                    '''
                ))

            if name is not None:
                if isinstance(name, dict):
                    if len(name) != 1:
                        raise ValueError(unwrap(
                            '''
                            When passing a dict as the "name" argument to %s,
                            it must have a single key/value - however %d were
                            present
                            ''',
                            type_name(self),
                            len(name)
                        ))
                    name, value = list(name.items())[0]

                if isinstance(name, tuple):
                    if len(name) != 2:
                        raise ValueError(unwrap(
                            '''
                            When passing a tuple as the "name" argument to %s,
                            it must have two elements, the name and value -
                            however %d were present
                            ''',
                            type_name(self),
                            len(name)
                        ))
                    value = name[1]
                    name = name[0]

                if name not in self._name_map:
                    raise ValueError(unwrap(
                        '''
                        The name specified, "%s", is not a valid alternative
                        for %s
                        ''',
                        name,
                        type_name(self)
                    ))

                self._choice = self._name_map[name]
                _, spec, params = self._alternatives[self._choice]

                if not isinstance(value, spec):
                    value = spec(value, **params)
                else:
                    value = _fix_tagging(value, params)
                self._parsed = value

        except (ValueError, TypeError) as e:
            args = e.args[1:]
            e.args = (e.args[0] + '\n    while constructing %s' % type_name(self),) + args
            raise e

    @property
    def contents(self):
        """
        :return:
            A byte string of the DER-encoded contents of the chosen alternative
        """

        if self._parsed is not None:
            return self._parsed.contents

        return self._contents

    @contents.setter
    def contents(self, value):
        """
        :param value:
            A byte string of the DER-encoded contents of the chosen alternative
        """

        self._contents = value

    @property
    def name(self):
        """
        :return:
            A unicode string of the field name of the chosen alternative
        """
        if not self._name:
            self._name = self._alternatives[self._choice][0]
        return self._name

    def parse(self):
        """
        Parses the detected alternative

        :return:
            An Asn1Value object of the chosen alternative
        """

        if self._parsed is None:
            try:
                _, spec, params = self._alternatives[self._choice]
                self._parsed, _ = _parse_build(self._contents, spec=spec, spec_params=params)
            except (ValueError, TypeError) as e:
                args = e.args[1:]
                e.args = (e.args[0] + '\n    while parsing %s' % type_name(self),) + args
                raise e
        return self._parsed

    @property
    def chosen(self):
        """
        :return:
            An Asn1Value object of the chosen alternative
        """

        return self.parse()

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            The .native value from the contained value object
        """

        return self.chosen.native

    def validate(self, class_, tag, contents):
        """
        Ensures that the class and tag specified exist as an alternative

        :param class_:
            The integer class_ from the encoded value header

        :param tag:
            The integer tag from the encoded value header

        :param contents:
            A byte string of the contents of the value - used when the object
            is explicitly tagged

        :raises:
            ValueError - when value is not a valid alternative
        """

        id_ = (class_, tag)

        if self.explicit is not None:
            if self.explicit[-1] != id_:
                raise ValueError(unwrap(
                    '''
                    %s was explicitly tagged, but the value provided does not
                    match the class and tag
                    ''',
                    type_name(self)
                ))

            ((class_, _, tag, _, _, _), _) = _parse(contents, len(contents))
            id_ = (class_, tag)

        if id_ in self._id_map:
            self._choice = self._id_map[id_]
            return

        # This means the Choice was implicitly tagged
        if self.class_ is not None and self.tag is not None:
            if len(self._alternatives) > 1:
                raise ValueError(unwrap(
                    '''
                    %s was implicitly tagged, but more than one alternative
                    exists
                    ''',
                    type_name(self)
                ))
            if id_ == (self.class_, self.tag):
                self._choice = 0
                return

        asn1 = self._format_class_tag(class_, tag)
        asn1s = [self._format_class_tag(pair[0], pair[1]) for pair in self._id_map]

        raise ValueError(unwrap(
            '''
            Value %s did not match the class and tag of any of the alternatives
            in %s: %s
            ''',
            asn1,
            type_name(self),
            ', '.join(asn1s)
        ))

    def _format_class_tag(self, class_, tag):
        """
        :return:
            A unicode string of a human-friendly representation of the class and tag
        """

        return '[%s %s]' % (CLASS_NUM_TO_NAME_MAP[class_].upper(), tag)

    def _copy(self, other, copy_func):
        """
        Copies the contents of another Choice object to itself

        :param object:
            Another instance of the same class

        :param copy_func:
            An reference of copy.copy() or copy.deepcopy() to use when copying
            lists, dicts and objects
        """

        super(Choice, self)._copy(other, copy_func)
        self._choice = other._choice
        self._name = other._name
        self._parsed = copy_func(other._parsed)

    def dump(self, force=False):
        """
        Encodes the value using DER

        :param force:
            If the encoded contents already exist, clear them and regenerate
            to ensure they are in DER format instead of BER format

        :return:
            A byte string of the DER-encoded value
        """

        # If the length is indefinite, force the re-encoding
        if self._header is not None and self._header[-1:] == b'\x80':
            force = True

        self._contents = self.chosen.dump(force=force)
        if self._header is None or force:
            self._header = b''
            if self.explicit is not None:
                for class_, tag in self.explicit:
                    self._header = _dump_header(class_, 1, tag, self._header + self._contents) + self._header
        return self._header + self._contents class Concat(object):
    """
    A class that contains two or more encoded child values concatentated
    together. THIS IS NOT PART OF THE ASN.1 SPECIFICATION! This exists to handle
    the x509.TrustedCertificate() class for OpenSSL certificates containing
    extra information.
    """

    # A list of the specs of the concatenated values
    _child_specs = None

    _children = None

    @classmethod
    def load(cls, encoded_data, strict=False):
        """
        Loads a BER/DER-encoded byte string using the current class as the spec

        :param encoded_data:
            A byte string of BER or DER encoded data

        :param strict:
            A boolean indicating if trailing data should be forbidden - if so, a
            ValueError will be raised when trailing data exists

        :return:
            A Concat object
        """

        return cls(contents=encoded_data, strict=strict)

    def __init__(self, value=None, contents=None, strict=False):
        """
        :param value:
            A native Python datatype to initialize the object value with

        :param contents:
            A byte string of the encoded contents of the value

        :param strict:
            A boolean indicating if trailing data should be forbidden - if so, a
            ValueError will be raised when trailing data exists in contents

        :raises:
            ValueError - when an error occurs with one of the children
            TypeError - when an error occurs with one of the children
        """

        if contents is not None:
            try:
                contents_len = len(contents)
                self._children = []

                offset = 0
                for spec in self._child_specs:
                    if offset < contents_len:
                        child_value, offset = _parse_build(contents, pointer=offset, spec=spec)
                    else:
                        child_value = spec()
                    self._children.append(child_value)

                if strict and offset != contents_len:
                    extra_bytes = contents_len - offset
                    raise ValueError('Extra data - %d bytes of trailing data were provided' % extra_bytes)

            except (ValueError, TypeError) as e:
                args = e.args[1:]
                e.args = (e.args[0] + '\n    while constructing %s' % type_name(self),) + args
                raise e

        if value is not None:
            if self._children is None:
                self._children = [None] * len(self._child_specs)
            for index, data in enumerate(value):
                self.__setitem__(index, data)

    def __str__(self):
        """
        Since str is different in Python 2 and 3, this calls the appropriate
        method, __unicode__() or __bytes__()

        :return:
            A unicode string
        """

        if _PY2:
            return self.__bytes__()
        else:
            return self.__unicode__()

    def __bytes__(self):
        """
        A byte string of the DER-encoded contents
        """

        return self.dump()

    def __unicode__(self):
        """
        :return:
            A unicode string
        """

        return repr(self)

    def __repr__(self):
        """
        :return:
            A unicode string
        """

        return '<%s %s %s>' % (type_name(self), id(self), repr(self.dump()))

    def __copy__(self):
        """
        Implements the copy.copy() interface

        :return:
            A new shallow copy of the Concat object
        """

        new_obj = self.__class__()
        new_obj._copy(self, copy.copy)
        return new_obj

    def __deepcopy__(self, memo):
        """
        Implements the copy.deepcopy() interface

        :param memo:
            A dict for memoization

        :return:
            A new deep copy of the Concat object and all child objects
        """

        new_obj = self.__class__()
        memo[id(self)] = new_obj
        new_obj._copy(self, copy.deepcopy)
        return new_obj

    def copy(self):
        """
        Copies the object

        :return:
            A Concat object
        """

        return copy.deepcopy(self)

    def _copy(self, other, copy_func):
        """
        Copies the contents of another Concat object to itself

        :param object:
            Another instance of the same class

        :param copy_func:
            An reference of copy.copy() or copy.deepcopy() to use when copying
            lists, dicts and objects
        """

        if self.__class__ != other.__class__:
            raise TypeError(unwrap(
                '''
                Can not copy values from %s object to %s object
                ''',
                type_name(other),
                type_name(self)
            ))

        self._children = copy_func(other._children)

    def debug(self, nest_level=1):
        """
        Show the binary data and parsed data in a tree structure
        """

        prefix = '  ' * nest_level
        print('%s%s Object #%s' % (prefix, type_name(self), id(self)))
        print('%s  Children:' % (prefix,))
        for child in self._children:
            child.debug(nest_level + 2)

    def dump(self, force=False):
        """
        Encodes the value using DER

        :param force:
            If the encoded contents already exist, clear them and regenerate
            to ensure they are in DER format instead of BER format

        :return:
            A byte string of the DER-encoded value
        """

        contents = b''
        for child in self._children:
            contents += child.dump(force=force)
        return contents

    @property
    def contents(self):
        """
        :return:
            A byte string of the DER-encoded contents of the children
        """

        return self.dump()

    def __len__(self):
        """
        :return:
            Integer
        """

        return len(self._children)

    def __getitem__(self, key):
        """
        Allows accessing children by index

        :param key:
            An integer of the child index

        :raises:
            KeyError - when an index is invalid

        :return:
            The Asn1Value object of the child specified
        """

        if key > len(self._child_specs) - 1 or key < 0:
            raise KeyError(unwrap(
                '''
                No child is definition for position %d of %s
                ''',
                key,
                type_name(self)
            ))

        return self._children[key]

    def __setitem__(self, key, value):
        """
        Allows settings children by index

        :param key:
            An integer of the child index

        :param value:
            An Asn1Value object to set the child to

        :raises:
            KeyError - when an index is invalid
            ValueError - when the value is not an instance of Asn1Value
        """

        if key > len(self._child_specs) - 1 or key < 0:
            raise KeyError(unwrap(
                '''
                No child is defined for position %d of %s
                ''',
                key,
                type_name(self)
            ))

        if not isinstance(value, Asn1Value):
            raise ValueError(unwrap(
                '''
                Value for child %s of %s is not an instance of
                asn1crypto.core.Asn1Value
                ''',
                key,
                type_name(self)
            ))

        self._children[key] = value

    def __iter__(self):
        """
        :return:
            An iterator of child values
        """

        return iter(self._children) class Enumerated(Integer):
    """
    Represents a enumerated list of integers from ASN.1 as a Python
    unicode string
    """

    tag = 10

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            An integer or a unicode string from _map

        :raises:
            ValueError - when an invalid value is passed
        """

        if not isinstance(value, int_types) and not isinstance(value, str_cls):
            raise TypeError(unwrap(
                '''
                %s value must be an integer or a unicode string, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        if isinstance(value, str_cls):
            if value not in self._reverse_map:
                raise ValueError(unwrap(
                    '''
                    %s value "%s" is not a valid value
                    ''',
                    type_name(self),
                    value
                ))

            value = self._reverse_map[value]

        elif value not in self._map:
            raise ValueError(unwrap(
                '''
                %s value %s is not a valid value
                ''',
                type_name(self),
                value
            ))

        Integer.set(self, value)

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            A unicode string or None
        """

        if self.contents is None:
            return None

        if self._native is None:
            self._native = self._map[self.__int__()]
        return self._native class GeneralizedTime(AbstractTime):
    """
    Represents a generalized time from ASN.1 as a Python datetime.datetime
    object or asn1crypto.util.extended_datetime object in UTC
    """

    tag = 24

    # Regular expression for GeneralizedTime as described in X.680 sect. 42 and ISO 8601
    _TIMESTRING_RE = re.compile(r'''
        ^
        # YYYYMMDD
        (?P<year>\d{4})
        (?P<month>\d{2})
        (?P<day>\d{2})

        # hh or hhmm or hhmmss
        (?P<hour>\d{2})
        (?:
            (?P<minute>\d{2})
            (?P<second>\d{2})?
        )?

        # Optional fraction; [.,]dddd (one or more decimals)
        # If Seconds are given, it's fractions of Seconds.
        # Else if Minutes are given, it's fractions of Minutes.
        # Else it's fractions of Hours.
        (?:
            [,.]
            (?P<fraction>\d+)
        )?

        # Optional timezone. If left out, the time is in local time.
        # Z or [-+]hh or [-+]hhmm
        (?:
            (?P<zulu>Z)
            |
            (?:
                (?P<dsign>[-+])
                (?P<dhour>\d{2})
                (?P<dminute>\d{2})?
            )
        )?
        $
    ''', re.X)

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            A unicode string, a datetime.datetime object or an
            asn1crypto.util.extended_datetime object

        :raises:
            ValueError - when an invalid value is passed
        """

        if isinstance(value, (datetime, extended_datetime)):
            if not value.tzinfo:
                raise ValueError('Must be timezone aware')

            # Convert value to UTC.
            value = value.astimezone(utc_with_dst)

            if value.microsecond:
                fraction = '.' + str(value.microsecond).zfill(6).rstrip('0')
            else:
                fraction = ''

            value = value.strftime('%Y%m%d%H%M%S') + fraction + 'Z'
            if _PY2:
                value = value.decode('ascii')

        AbstractString.set(self, value)
        # Set it to None and let the class take care of converting the next
        # time that .native is called
        self._native = None

    def _get_datetime(self, parsed):
        """
        Create a datetime object from the parsed time.

        :return:
            A datetime.datetime object or asn1crypto.util.extended_datetime object.
            It may or may not be aware.
        """

        if parsed['year'] == 0:
            # datetime does not support year 0. Use extended_datetime instead.
            return extended_datetime(**parsed)
        else:
            return datetime(**parsed) class GeneralString(AbstractString):
    """
    Represents a general string from ASN.1 as a Python unicode string
    """

    tag = 27
    # This is technically not correct since this type can contain any charset
    _encoding = 'latin1' class IA5String(AbstractString):
    """
    Represents an IA5 string from ASN.1 as a Python unicode string
    """

    tag = 22
    _encoding = 'ascii' class Integer(Primitive, ValueMap):
    """
    Represents an integer in both ASN.1 and Python
    """

    tag = 2

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            An integer, or a unicode string if _map is set

        :raises:
            ValueError - when an invalid value is passed
        """

        if isinstance(value, str_cls):
            if self._map is None:
                raise ValueError(unwrap(
                    '''
                    %s value is a unicode string, but no _map provided
                    ''',
                    type_name(self)
                ))

            if value not in self._reverse_map:
                raise ValueError(unwrap(
                    '''
                    %s value, %s, is not present in the _map
                    ''',
                    type_name(self),
                    value
                ))

            value = self._reverse_map[value]

        elif not isinstance(value, int_types):
            raise TypeError(unwrap(
                '''
                %s value must be an integer or unicode string when a name_map
                is provided, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        self._native = self._map[value] if self._map and value in self._map else value

        self.contents = int_to_bytes(value, signed=True)
        self._header = None
        if self._trailer != b'':
            self._trailer = b''

    def __int__(self):
        """
        :return:
            An integer
        """
        return int_from_bytes(self.contents, signed=True)

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            An integer or None
        """

        if self.contents is None:
            return None

        if self._native is None:
            self._native = self.__int__()
            if self._map is not None and self._native in self._map:
                self._native = self._map[self._native]
        return self._native class Null(Primitive):
    """
    Represents a null value in ASN.1 as None in Python
    """

    tag = 5

    contents = b''

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            None
        """

        self.contents = b''

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            None
        """

        return None class NumericString(AbstractString):
    """
    Represents a numeric string from ASN.1 as a Python unicode string
    """

    tag = 18
    _encoding = 'latin1' class ObjectIdentifier(Primitive, ValueMap):
    """
    Represents an object identifier in ASN.1 as a Python unicode dotted
    integer string
    """

    tag = 6

    # A unicode string of the dotted form of the object identifier
    _dotted = None

    @classmethod
    def map(cls, value):
        """
        Converts a dotted unicode string OID into a mapped unicode string

        :param value:
            A dotted unicode string OID

        :raises:
            ValueError - when no _map dict has been defined on the class
            TypeError - when value is not a unicode string

        :return:
            A mapped unicode string
        """

        if cls._map is None:
            raise ValueError(unwrap(
                '''
                %s._map has not been defined
                ''',
                type_name(cls)
            ))

        if not isinstance(value, str_cls):
            raise TypeError(unwrap(
                '''
                value must be a unicode string, not %s
                ''',
                type_name(value)
            ))

        return cls._map.get(value, value)

    @classmethod
    def unmap(cls, value):
        """
        Converts a mapped unicode string value into a dotted unicode string OID

        :param value:
            A mapped unicode string OR dotted unicode string OID

        :raises:
            ValueError - when no _map dict has been defined on the class or the value can't be unmapped
            TypeError - when value is not a unicode string

        :return:
            A dotted unicode string OID
        """

        if cls not in _SETUP_CLASSES:
            cls()._setup()
            _SETUP_CLASSES[cls] = True

        if cls._map is None:
            raise ValueError(unwrap(
                '''
                %s._map has not been defined
                ''',
                type_name(cls)
            ))

        if not isinstance(value, str_cls):
            raise TypeError(unwrap(
                '''
                value must be a unicode string, not %s
                ''',
                type_name(value)
            ))

        if value in cls._reverse_map:
            return cls._reverse_map[value]

        if not _OID_RE.match(value):
            raise ValueError(unwrap(
                '''
                %s._map does not contain an entry for "%s"
                ''',
                type_name(cls),
                value
            ))

        return value

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            A unicode string. May be a dotted integer string, or if _map is
            provided, one of the mapped values.

        :raises:
            ValueError - when an invalid value is passed
        """

        if not isinstance(value, str_cls):
            raise TypeError(unwrap(
                '''
                %s value must be a unicode string, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        self._native = value

        if self._map is not None:
            if value in self._reverse_map:
                value = self._reverse_map[value]

        self.contents = b''
        first = None
        for index, part in enumerate(value.split('.')):
            part = int(part)

            # The first two parts are merged into a single byte
            if index == 0:
                first = part
                continue
            elif index == 1:
                if first > 2:
                    raise ValueError(unwrap(
                        '''
                        First arc must be one of 0, 1 or 2, not %s
                        ''',
                        repr(first)
                    ))
                elif first < 2 and part >= 40:
                    raise ValueError(unwrap(
                        '''
                        Second arc must be less than 40 if first arc is 0 or
                        1, not %s
                        ''',
                        repr(part)
                    ))
                part = (first * 40) + part

            encoded_part = chr_cls(0x7F & part)
            part = part >> 7
            while part > 0:
                encoded_part = chr_cls(0x80 | (0x7F & part)) + encoded_part
                part = part >> 7
            self.contents += encoded_part

        self._header = None
        if self._trailer != b'':
            self._trailer = b''

    def __unicode__(self):
        """
        :return:
            A unicode string
        """

        return self.dotted

    @property
    def dotted(self):
        """
        :return:
            A unicode string of the object identifier in dotted notation, thus
            ignoring any mapped value
        """

        if self._dotted is None:
            output = []

            part = 0
            for byte in self.contents:
                if _PY2:
                    byte = ord(byte)
                part = part * 128
                part += byte & 127
                # Last byte in subidentifier has the eighth bit set to 0
                if byte & 0x80 == 0:
                    if len(output) == 0:
                        if part >= 80:
                            output.append(str_cls(2))
                            output.append(str_cls(part - 80))
                        elif part >= 40:
                            output.append(str_cls(1))
                            output.append(str_cls(part - 40))
                        else:
                            output.append(str_cls(0))
                            output.append(str_cls(part))
                    else:
                        output.append(str_cls(part))
                    part = 0

            self._dotted = '.'.join(output)
        return self._dotted

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            A unicode string or None. If _map is not defined, the unicode string
            is a string of dotted integers. If _map is defined and the dotted
            string is present in the _map, the mapped value is returned.
        """

        if self.contents is None:
            return None

        if self._native is None:
            self._native = self.dotted
        if self._map is not None and self._native in self._map:
            self._native = self._map[self._native]
        return self._native class OctetBitString(Constructable, Castable, Primitive):
    """
    Represents a bit string in ASN.1 as a Python byte string
    """

    tag = 3

    # Instance attribute of (possibly-merged) byte string
    _bytes = None

    # Tuple of 1s and 0s; set through native
    _unused_bits = ()

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            A byte string

        :raises:
            ValueError - when an invalid value is passed
        """

        if not isinstance(value, byte_cls):
            raise TypeError(unwrap(
                '''
                %s value must be a byte string, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        self._bytes = value
        # Set the unused bits to 0
        self.contents = b'\x00' + value
        self._unused_bits = ()
        self._header = None
        if self._indefinite:
            self._indefinite = False
            self.method = 0
        if self._trailer != b'':
            self._trailer = b''

    def __bytes__(self):
        """
        :return:
            A byte string
        """

        if self.contents is None:
            return b''
        if self._bytes is None:
            if not self._indefinite:
                self._bytes, self._unused_bits = self._as_chunk()[0]
            else:
                chunks = self._merge_chunks()
                self._unused_bits = ()
                for chunk in chunks:
                    if self._unused_bits:
                        # Disallowed by X.690 §8.6.4
                        raise ValueError('Only last chunk in a bit string may have unused bits')
                    self._unused_bits = chunk[1]
                self._bytes = b''.join(chunk[0] for chunk in chunks)

        return self._bytes

    def _copy(self, other, copy_func):
        """
        Copies the contents of another OctetBitString object to itself

        :param object:
            Another instance of the same class

        :param copy_func:
            An reference of copy.copy() or copy.deepcopy() to use when copying
            lists, dicts and objects
        """

        super(OctetBitString, self)._copy(other, copy_func)
        self._bytes = other._bytes
        self._unused_bits = other._unused_bits

    def _as_chunk(self):
        """
        Allows reconstructing indefinite length values

        :raises:
            ValueError - when an invalid value is passed

        :return:
            List with one tuple, consisting of a byte string and an integer (unused bits)
        """

        unused_bits_len = ord(self.contents[0]) if _PY2 else self.contents[0]
        if not unused_bits_len:
            return [(self.contents[1:], ())]

        if len(self.contents) == 1:
            # Disallowed by X.690 §8.6.2.3
            raise ValueError('Empty bit string has {0} unused bits'.format(unused_bits_len))

        if unused_bits_len > 7:
            # Disallowed by X.690 §8.6.2.2
            raise ValueError('Bit string has {0} unused bits'.format(unused_bits_len))

        mask = (1 << unused_bits_len) - 1
        last_byte = ord(self.contents[-1]) if _PY2 else self.contents[-1]

        # zero out the unused bits in the last byte.
        zeroed_byte = last_byte & ~mask
        value = self.contents[1:-1] + (chr(zeroed_byte) if _PY2 else bytes((zeroed_byte,)))

        unused_bits = _int_to_bit_tuple(last_byte & mask, unused_bits_len)

        return [(value, unused_bits)]

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            A byte string or None
        """

        if self.contents is None:
            return None

        return self.__bytes__()

    @property
    def unused_bits(self):
        """
        The unused bits of the bit string encoding.

        :return:
            A tuple of 1s and 0s
        """

        # call native to set _unused_bits
        self.native

        return self._unused_bits class OctetString(Constructable, Castable, Primitive):
    """
    Represents a byte string in both ASN.1 and Python
    """

    tag = 4

    # Instance attribute of (possibly-merged) byte string
    _bytes = None

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            A byte string
        """

        if not isinstance(value, byte_cls):
            raise TypeError(unwrap(
                '''
                %s value must be a byte string, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        self._bytes = value
        self.contents = value
        self._header = None
        if self._indefinite:
            self._indefinite = False
            self.method = 0
        if self._trailer != b'':
            self._trailer = b''

    def __bytes__(self):
        """
        :return:
            A byte string
        """

        if self.contents is None:
            return b''
        if self._bytes is None:
            self._bytes = self._merge_chunks()
        return self._bytes

    def _copy(self, other, copy_func):
        """
        Copies the contents of another OctetString object to itself

        :param object:
            Another instance of the same class

        :param copy_func:
            An reference of copy.copy() or copy.deepcopy() to use when copying
            lists, dicts and objects
        """

        super(OctetString, self)._copy(other, copy_func)
        self._bytes = other._bytes

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            A byte string or None
        """

        if self.contents is None:
            return None

        return self.__bytes__() class ParsableOctetString(Constructable, Castable, Primitive):

    tag = 4

    _parsed = None

    # Instance attribute of (possibly-merged) byte string
    _bytes = None

    def __init__(self, value=None, parsed=None, **kwargs):
        """
        Allows providing a parsed object that will be serialized to get the
        byte string value

        :param value:
            A native Python datatype to initialize the object value with

        :param parsed:
            If value is None and this is an Asn1Value object, this will be
            set as the parsed value, and the value will be obtained by calling
            .dump() on this object.
        """

        set_parsed = False
        if value is None and parsed is not None and isinstance(parsed, Asn1Value):
            value = parsed.dump()
            set_parsed = True

        Primitive.__init__(self, value=value, **kwargs)

        if set_parsed:
            self._parsed = (parsed, parsed.__class__, None)

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            A byte string
        """

        if not isinstance(value, byte_cls):
            raise TypeError(unwrap(
                '''
                %s value must be a byte string, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        self._bytes = value
        self.contents = value
        self._header = None
        if self._indefinite:
            self._indefinite = False
            self.method = 0
        if self._trailer != b'':
            self._trailer = b''

    def parse(self, spec=None, spec_params=None):
        """
        Parses the contents generically, or using a spec with optional params

        :param spec:
            A class derived from Asn1Value that defines what class_ and tag the
            value should have, and the semantics of the encoded value. The
            return value will be of this type. If omitted, the encoded value
            will be decoded using the standard universal tag based on the
            encoded tag number.

        :param spec_params:
            A dict of params to pass to the spec object

        :return:
            An object of the type spec, or if not present, a child of Asn1Value
        """

        if self._parsed is None or self._parsed[1:3] != (spec, spec_params):
            parsed_value, _ = _parse_build(self.__bytes__(), spec=spec, spec_params=spec_params)
            self._parsed = (parsed_value, spec, spec_params)
        return self._parsed[0]

    def __bytes__(self):
        """
        :return:
            A byte string
        """

        if self.contents is None:
            return b''
        if self._bytes is None:
            self._bytes = self._merge_chunks()
        return self._bytes

    def _setable_native(self):
        """
        Returns a byte string that can be passed into .set()

        :return:
            A python value that is valid to pass to .set()
        """

        return self.__bytes__()

    def _copy(self, other, copy_func):
        """
        Copies the contents of another ParsableOctetString object to itself

        :param object:
            Another instance of the same class

        :param copy_func:
            An reference of copy.copy() or copy.deepcopy() to use when copying
            lists, dicts and objects
        """

        super(ParsableOctetString, self)._copy(other, copy_func)
        self._bytes = other._bytes
        self._parsed = copy_func(other._parsed)

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            A byte string or None
        """

        if self.contents is None:
            return None

        if self._parsed is not None:
            return self._parsed[0].native
        else:
            return self.__bytes__()

    @property
    def parsed(self):
        """
        Returns the parsed object from .parse()

        :return:
            The object returned by .parse()
        """

        if self._parsed is None:
            self.parse()

        return self._parsed[0]

    def dump(self, force=False):
        """
        Encodes the value using DER

        :param force:
            If the encoded contents already exist, clear them and regenerate
            to ensure they are in DER format instead of BER format

        :return:
            A byte string of the DER-encoded value
        """

        # If the length is indefinite, force the re-encoding
        if self._indefinite:
            force = True

        if force:
            if self._parsed is not None:
                native = self.parsed.dump(force=force)
            else:
                native = self.native
            self.contents = None
            self.set(native)

        return Asn1Value.dump(self) class PrintableString(AbstractString):
    """
    Represents a printable string from ASN.1 as a Python unicode string
    """

    tag = 19
    _encoding = 'latin1' class Sequence(Asn1Value):
    """
    Represents a sequence of fields from ASN.1 as a Python object with a
    dict-like interface
    """

    tag = 16

    class_ = 0
    method = 1

    # A list of child objects, in order of _fields
    children = None

    # Sequence overrides .contents to be a property so that the mutated state
    # of child objects can be checked to ensure everything is up-to-date
    _contents = None

    # Variable to track if the object has been mutated
    _mutated = False

    # A list of tuples in one of the following forms.
    #
    # Option 1, a unicode string field name and a value class
    #
    # ("name", Asn1ValueClass)
    #
    # Option 2, same as Option 1, but with a dict of class params
    #
    # ("name", Asn1ValueClass, {'explicit': 5})
    _fields = []

    # A dict with keys being the name of a field and the value being a unicode
    # string of the method name on self to call to get the spec for that field
    _spec_callbacks = None

    # A dict that maps unicode string field names to an index in _fields
    _field_map = None

    # A list in the same order as _fields that has tuples in the form (class_, tag)
    _field_ids = None

    # An optional 2-element tuple that defines the field names of an OID field
    # and the field that the OID should be used to help decode. Works with the
    # _oid_specs attribute.
    _oid_pair = None

    # A dict with keys that are unicode string OID values and values that are
    # Asn1Value classes to use for decoding a variable-type field.
    _oid_specs = None

    # A 2-element tuple of the indexes in _fields of the OID and value fields
    _oid_nums = None

    # Predetermined field specs to optimize away calls to _determine_spec()
    _precomputed_specs = None

    def __init__(self, value=None, default=None, **kwargs):
        """
        Allows setting field values before passing everything else along to
        Asn1Value.__init__()

        :param value:
            A native Python datatype to initialize the object value with

        :param default:
            The default value if no value is specified
        """

        Asn1Value.__init__(self, **kwargs)

        check_existing = False
        if value is None and default is not None:
            check_existing = True
            if self.children is None:
                if self.contents is None:
                    check_existing = False
                else:
                    self._parse_children()
            value = default

        if value is not None:
            try:
                # Fields are iterated in definition order to allow things like
                # OID-based specs. Otherwise sometimes the value would be processed
                # before the OID field, resulting in invalid value object creation.
                if self._fields:
                    keys = [info[0] for info in self._fields]
                    unused_keys = set(value.keys())
                else:
                    keys = value.keys()
                    unused_keys = set(keys)

                for key in keys:
                    # If we are setting defaults, but a real value has already
                    # been set for the field, then skip it
                    if check_existing:
                        index = self._field_map[key]
                        if index < len(self.children) and self.children[index] is not VOID:
                            if key in unused_keys:
                                unused_keys.remove(key)
                            continue

                    if key in value:
                        self.__setitem__(key, value[key])
                        unused_keys.remove(key)

                if len(unused_keys):
                    raise ValueError(unwrap(
                        '''
                        One or more unknown fields was passed to the constructor
                        of %s: %s
                        ''',
                        type_name(self),
                        ', '.join(sorted(list(unused_keys)))
                    ))

            except (ValueError, TypeError) as e:
                args = e.args[1:]
                e.args = (e.args[0] + '\n    while constructing %s' % type_name(self),) + args
                raise e

    @property
    def contents(self):
        """
        :return:
            A byte string of the DER-encoded contents of the sequence
        """

        if self.children is None:
            return self._contents

        if self._is_mutated():
            self._set_contents()

        return self._contents

    @contents.setter
    def contents(self, value):
        """
        :param value:
            A byte string of the DER-encoded contents of the sequence
        """

        self._contents = value

    def _is_mutated(self):
        """
        :return:
            A boolean - if the sequence or any children (recursively) have been
            mutated
        """

        mutated = self._mutated
        if self.children is not None:
            for child in self.children:
                if isinstance(child, Sequence) or isinstance(child, SequenceOf):
                    mutated = mutated or child._is_mutated()

        return mutated

    def _lazy_child(self, index):
        """
        Builds a child object if the child has only been parsed into a tuple so far
        """

        child = self.children[index]
        if child.__class__ == tuple:
            child = self.children[index] = _build(*child)
        return child

    def __len__(self):
        """
        :return:
            Integer
        """
        # We inline this check to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        return len(self.children)

    def __getitem__(self, key):
        """
        Allows accessing fields by name or index

        :param key:
            A unicode string of the field name, or an integer of the field index

        :raises:
            KeyError - when a field name or index is invalid

        :return:
            The Asn1Value object of the field specified
        """

        # We inline this check to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        if not isinstance(key, int_types):
            if key not in self._field_map:
                raise KeyError(unwrap(
                    '''
                    No field named "%s" defined for %s
                    ''',
                    key,
                    type_name(self)
                ))
            key = self._field_map[key]

        if key >= len(self.children):
            raise KeyError(unwrap(
                '''
                No field numbered %s is present in this %s
                ''',
                key,
                type_name(self)
            ))

        try:
            return self._lazy_child(key)

        except (ValueError, TypeError) as e:
            args = e.args[1:]
            e.args = (e.args[0] + '\n    while parsing %s' % type_name(self),) + args
            raise e

    def __setitem__(self, key, value):
        """
        Allows settings fields by name or index

        :param key:
            A unicode string of the field name, or an integer of the field index

        :param value:
            A native Python datatype to set the field value to. This method will
            construct the appropriate Asn1Value object from _fields.

        :raises:
            ValueError - when a field name or index is invalid
        """

        # We inline this check to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        if not isinstance(key, int_types):
            if key not in self._field_map:
                raise KeyError(unwrap(
                    '''
                    No field named "%s" defined for %s
                    ''',
                    key,
                    type_name(self)
                ))
            key = self._field_map[key]

        field_name, field_spec, value_spec, field_params, _ = self._determine_spec(key)

        new_value = self._make_value(field_name, field_spec, value_spec, field_params, value)

        invalid_value = False
        if isinstance(new_value, Any):
            invalid_value = new_value.parsed is None
        else:
            invalid_value = new_value.contents is None

        if invalid_value:
            raise ValueError(unwrap(
                '''
                Value for field "%s" of %s is not set
                ''',
                field_name,
                type_name(self)
            ))

        self.children[key] = new_value

        if self._native is not None:
            self._native[self._fields[key][0]] = self.children[key].native
        self._mutated = True

    def __delitem__(self, key):
        """
        Allows deleting optional or default fields by name or index

        :param key:
            A unicode string of the field name, or an integer of the field index

        :raises:
            ValueError - when a field name or index is invalid, or the field is not optional or defaulted
        """

        # We inline this check to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        if not isinstance(key, int_types):
            if key not in self._field_map:
                raise KeyError(unwrap(
                    '''
                    No field named "%s" defined for %s
                    ''',
                    key,
                    type_name(self)
                ))
            key = self._field_map[key]

        name, _, params = self._fields[key]
        if not params or ('default' not in params and 'optional' not in params):
            raise ValueError(unwrap(
                '''
                Can not delete the value for the field "%s" of %s since it is
                not optional or defaulted
                ''',
                name,
                type_name(self)
            ))

        if 'optional' in params:
            self.children[key] = VOID
            if self._native is not None:
                self._native[name] = None
        else:
            self.__setitem__(key, None)
        self._mutated = True

    def __iter__(self):
        """
        :return:
            An iterator of field key names
        """

        for info in self._fields:
            yield info[0]

    def _set_contents(self, force=False):
        """
        Updates the .contents attribute of the value with the encoded value of
        all of the child objects

        :param force:
            Ensure all contents are in DER format instead of possibly using
            cached BER-encoded data
        """

        if self.children is None:
            self._parse_children()

        contents = BytesIO()
        for index, info in enumerate(self._fields):
            child = self.children[index]
            if child is None:
                child_dump = b''
            elif child.__class__ == tuple:
                if force:
                    child_dump = self._lazy_child(index).dump(force=force)
                else:
                    child_dump = child[3] + child[4] + child[5]
            else:
                child_dump = child.dump(force=force)
            # Skip values that are the same as the default
            if info[2] and 'default' in info[2]:
                default_value = info[1](**info[2])
                if default_value.dump() == child_dump:
                    continue
            contents.write(child_dump)
        self._contents = contents.getvalue()

        self._header = None
        if self._trailer != b'':
            self._trailer = b''

    def _setup(self):
        """
        Generates _field_map, _field_ids and _oid_nums for use in parsing
        """

        cls = self.__class__
        cls._field_map = {}
        cls._field_ids = []
        cls._precomputed_specs = []
        for index, field in enumerate(cls._fields):
            if len(field) < 3:
                field = field + ({},)
                cls._fields[index] = field
            cls._field_map[field[0]] = index
            cls._field_ids.append(_build_id_tuple(field[2], field[1]))

        if cls._oid_pair is not None:
            cls._oid_nums = (cls._field_map[cls._oid_pair[0]], cls._field_map[cls._oid_pair[1]])

        for index, field in enumerate(cls._fields):
            has_callback = cls._spec_callbacks is not None and field[0] in cls._spec_callbacks
            is_mapped_oid = cls._oid_nums is not None and cls._oid_nums[1] == index
            if has_callback or is_mapped_oid:
                cls._precomputed_specs.append(None)
            else:
                cls._precomputed_specs.append((field[0], field[1], field[1], field[2], None))

    def _determine_spec(self, index):
        """
        Determine how a value for a field should be constructed

        :param index:
            The field number

        :return:
            A tuple containing the following elements:
             - unicode string of the field name
             - Asn1Value class of the field spec
             - Asn1Value class of the value spec
             - None or dict of params to pass to the field spec
             - None or Asn1Value class indicating the value spec was derived from an OID or a spec callback
        """

        name, field_spec, field_params = self._fields[index]
        value_spec = field_spec
        spec_override = None

        if self._spec_callbacks is not None and name in self._spec_callbacks:
            callback = self._spec_callbacks[name]
            spec_override = callback(self)
            if spec_override:
                # Allow a spec callback to specify both the base spec and
                # the override, for situations such as OctetString and parse_as
                if spec_override.__class__ == tuple and len(spec_override) == 2:
                    field_spec, value_spec = spec_override
                    if value_spec is None:
                        value_spec = field_spec
                        spec_override = None
                # When no field spec is specified, use a single return value as that
                elif field_spec is None:
                    field_spec = spec_override
                    value_spec = field_spec
                    spec_override = None
                else:
                    value_spec = spec_override

        elif self._oid_nums is not None and self._oid_nums[1] == index:
            oid = self._lazy_child(self._oid_nums[0]).native
            if oid in self._oid_specs:
                spec_override = self._oid_specs[oid]
                value_spec = spec_override

        return (name, field_spec, value_spec, field_params, spec_override)

    def _make_value(self, field_name, field_spec, value_spec, field_params, value):
        """
        Contructs an appropriate Asn1Value object for a field

        :param field_name:
            A unicode string of the field name

        :param field_spec:
            An Asn1Value class that is the field spec

        :param value_spec:
            An Asn1Value class that is the vaue spec

        :param field_params:
            None or a dict of params for the field spec

        :param value:
            The value to construct an Asn1Value object from

        :return:
            An instance of a child class of Asn1Value
        """

        if value is None and 'optional' in field_params:
            return VOID

        specs_different = field_spec != value_spec
        is_any = issubclass(field_spec, Any)

        if issubclass(value_spec, Choice):
            is_asn1value = isinstance(value, Asn1Value)
            is_tuple = isinstance(value, tuple) and len(value) == 2
            is_dict = isinstance(value, dict) and len(value) == 1
            if not is_asn1value and not is_tuple and not is_dict:
                raise ValueError(unwrap(
                    '''
                    Can not set a native python value to %s, which has the
                    choice type of %s - value must be an instance of Asn1Value
                    ''',
                    field_name,
                    type_name(value_spec)
                ))
            if is_tuple or is_dict:
                value = value_spec(value)
            if not isinstance(value, value_spec):
                wrapper = value_spec()
                wrapper.validate(value.class_, value.tag, value.contents)
                wrapper._parsed = value
                new_value = wrapper
            else:
                new_value = value

        elif isinstance(value, field_spec):
            new_value = value
            if specs_different:
                new_value.parse(value_spec)

        elif (not specs_different or is_any) and not isinstance(value, value_spec):
            if (not is_any or specs_different) and isinstance(value, Asn1Value):
                raise TypeError(unwrap(
                    '''
                    %s value must be %s, not %s
                    ''',
                    field_name,
                    type_name(value_spec),
                    type_name(value)
                ))
            new_value = value_spec(value, **field_params)

        else:
            if isinstance(value, value_spec):
                new_value = value
            else:
                if isinstance(value, Asn1Value):
                    raise TypeError(unwrap(
                        '''
                        %s value must be %s, not %s
                        ''',
                        field_name,
                        type_name(value_spec),
                        type_name(value)
                    ))
                new_value = value_spec(value)

            # For when the field is OctetString or OctetBitString with embedded
            # values we need to wrap the value in the field spec to get the
            # appropriate encoded value.
            if specs_different and not is_any:
                wrapper = field_spec(value=new_value.dump(), **field_params)
                wrapper._parsed = (new_value, new_value.__class__, None)
                new_value = wrapper

        new_value = _fix_tagging(new_value, field_params)

        return new_value

    def _parse_children(self, recurse=False):
        """
        Parses the contents and generates Asn1Value objects based on the
        definitions from _fields.

        :param recurse:
            If child objects that are Sequence or SequenceOf objects should
            be recursively parsed

        :raises:
            ValueError - when an error occurs parsing child objects
        """

        cls = self.__class__
        if self._contents is None:
            if self._fields:
                self.children = [VOID] * len(self._fields)
                for index, (_, _, params) in enumerate(self._fields):
                    if 'default' in params:
                        if cls._precomputed_specs[index]:
                            field_name, field_spec, value_spec, field_params, _ = cls._precomputed_specs[index]
                        else:
                            field_name, field_spec, value_spec, field_params, _ = self._determine_spec(index)
                        self.children[index] = self._make_value(field_name, field_spec, value_spec, field_params, None)
            return

        try:
            self.children = []
            contents_length = len(self._contents)
            child_pointer = 0
            field = 0
            field_len = len(self._fields)
            parts = None
            again = child_pointer < contents_length
            while again:
                if parts is None:
                    parts, child_pointer = _parse(self._contents, contents_length, pointer=child_pointer)
                again = child_pointer < contents_length

                if field < field_len:
                    _, field_spec, value_spec, field_params, spec_override = (
                        cls._precomputed_specs[field] or self._determine_spec(field))

                    # If the next value is optional or default, allow it to be absent
                    if field_params and ('optional' in field_params or 'default' in field_params):
                        if self._field_ids[field] != (parts[0], parts[2]) and field_spec != Any:

                            # See if the value is a valid choice before assuming
                            # that we have a missing optional or default value
                            choice_match = False
                            if issubclass(field_spec, Choice):
                                try:
                                    tester = field_spec(**field_params)
                                    tester.validate(parts[0], parts[2], parts[4])
                                    choice_match = True
                                except (ValueError):
                                    pass

                            if not choice_match:
                                if 'optional' in field_params:
                                    self.children.append(VOID)
                                else:
                                    self.children.append(field_spec(**field_params))
                                field += 1
                                again = True
                                continue

                    if field_spec is None or (spec_override and issubclass(field_spec, Any)):
                        field_spec = value_spec
                        spec_override = None

                    if spec_override:
                        child = parts + (field_spec, field_params, value_spec)
                    else:
                        child = parts + (field_spec, field_params)

                # Handle situations where an optional or defaulted field definition is incorrect
                elif field_len > 0 and field + 1 <= field_len:
                    missed_fields = []
                    prev_field = field - 1
                    while prev_field >= 0:
                        prev_field_info = self._fields[prev_field]
                        if len(prev_field_info) < 3:
                            break
                        if 'optional' in prev_field_info[2] or 'default' in prev_field_info[2]:
                            missed_fields.append(prev_field_info[0])
                        prev_field -= 1
                    plural = 's' if len(missed_fields) > 1 else ''
                    missed_field_names = ', '.join(missed_fields)
                    raise ValueError(unwrap(
                        '''
                        Data for field %s (%s class, %s method, tag %s) does
                        not match the field definition%s of %s
                        ''',
                        field + 1,
                        CLASS_NUM_TO_NAME_MAP.get(parts[0]),
                        METHOD_NUM_TO_NAME_MAP.get(parts[1]),
                        parts[2],
                        plural,
                        missed_field_names
                    ))

                else:
                    child = parts

                if recurse:
                    child = _build(*child)
                    if isinstance(child, (Sequence, SequenceOf)):
                        child._parse_children(recurse=True)

                self.children.append(child)
                field += 1
                parts = None

            index = len(self.children)
            while index < field_len:
                name, field_spec, field_params = self._fields[index]
                if 'default' in field_params:
                    self.children.append(field_spec(**field_params))
                elif 'optional' in field_params:
                    self.children.append(VOID)
                else:
                    raise ValueError(unwrap(
                        '''
                        Field "%s" is missing from structure
                        ''',
                        name
                    ))
                index += 1

        except (ValueError, TypeError) as e:
            self.children = None
            args = e.args[1:]
            e.args = (e.args[0] + '\n    while parsing %s' % type_name(self),) + args
            raise e

    def spec(self, field_name):
        """
        Determines the spec to use for the field specified. Depending on how
        the spec is determined (_oid_pair or _spec_callbacks), it may be
        necessary to set preceding field values before calling this. Usually
        specs, if dynamic, are controlled by a preceding ObjectIdentifier
        field.

        :param field_name:
            A unicode string of the field name to get the spec for

        :return:
            A child class of asn1crypto.core.Asn1Value that the field must be
            encoded using
        """

        if not isinstance(field_name, str_cls):
            raise TypeError(unwrap(
                '''
                field_name must be a unicode string, not %s
                ''',
                type_name(field_name)
            ))

        if self._fields is None:
            raise ValueError(unwrap(
                '''
                Unable to retrieve spec for field %s in the class %s because
                _fields has not been set
                ''',
                repr(field_name),
                type_name(self)
            ))

        index = self._field_map[field_name]
        info = self._determine_spec(index)

        return info[2]

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            An OrderedDict or None. If an OrderedDict, all child values are
            recursively converted to native representation also.
        """

        if self.contents is None:
            return None

        if self._native is None:
            if self.children is None:
                self._parse_children(recurse=True)
            try:
                self._native = OrderedDict()
                for index, child in enumerate(self.children):
                    if child.__class__ == tuple:
                        child = _build(*child)
                        self.children[index] = child
                    try:
                        name = self._fields[index][0]
                    except (IndexError):
                        name = str_cls(index)
                    self._native[name] = child.native
            except (ValueError, TypeError) as e:
                self._native = None
                args = e.args[1:]
                e.args = (e.args[0] + '\n    while parsing %s' % type_name(self),) + args
                raise e
        return self._native

    def _copy(self, other, copy_func):
        """
        Copies the contents of another Sequence object to itself

        :param object:
            Another instance of the same class

        :param copy_func:
            An reference of copy.copy() or copy.deepcopy() to use when copying
            lists, dicts and objects
        """

        super(Sequence, self)._copy(other, copy_func)
        if self.children is not None:
            self.children = []
            for child in other.children:
                if child.__class__ == tuple:
                    self.children.append(child)
                else:
                    self.children.append(child.copy())

    def debug(self, nest_level=1):
        """
        Show the binary data and parsed data in a tree structure
        """

        if self.children is None:
            self._parse_children()

        prefix = '  ' * nest_level
        _basic_debug(prefix, self)
        for field_name in self:
            child = self._lazy_child(self._field_map[field_name])
            if child is not VOID:
                print('%s    Field "%s"' % (prefix, field_name))
                child.debug(nest_level + 3)

    def dump(self, force=False):
        """
        Encodes the value using DER

        :param force:
            If the encoded contents already exist, clear them and regenerate
            to ensure they are in DER format instead of BER format

        :return:
            A byte string of the DER-encoded value
        """

        # If the length is indefinite, force the re-encoding
        if self._header is not None and self._header[-1:] == b'\x80':
            force = True

        # We can't force encoding if we don't have a spec
        if force and self._fields == [] and self.__class__ is Sequence:
            force = False

        if force:
            self._set_contents(force=force)

        if self._fields and self.children is not None:
            for index, (field_name, _, params) in enumerate(self._fields):
                if self.children[index] is not VOID:
                    continue
                if 'default' in params or 'optional' in params:
                    continue
                raise ValueError(unwrap(
                    '''
                    Field "%s" is missing from structure
                    ''',
                    field_name
                ))

        return Asn1Value.dump(self) class SequenceOf(Asn1Value):
    """
    Represents a sequence (ordered) of a single type of values from ASN.1 as a
    Python object with a list-like interface
    """

    tag = 16

    class_ = 0
    method = 1

    # A list of child objects
    children = None

    # SequenceOf overrides .contents to be a property so that the mutated state
    # of child objects can be checked to ensure everything is up-to-date
    _contents = None

    # Variable to track if the object has been mutated
    _mutated = False

    # An Asn1Value class to use when parsing children
    _child_spec = None

    def __init__(self, value=None, default=None, contents=None, spec=None, **kwargs):
        """
        Allows setting child objects and the _child_spec via the spec parameter
        before passing everything else along to Asn1Value.__init__()

        :param value:
            A native Python datatype to initialize the object value with

        :param default:
            The default value if no value is specified

        :param contents:
            A byte string of the encoded contents of the value

        :param spec:
            A class derived from Asn1Value to use to parse children
        """

        if spec:
            self._child_spec = spec

        Asn1Value.__init__(self, **kwargs)

        try:
            if contents is not None:
                self.contents = contents
            else:
                if value is None and default is not None:
                    value = default

                if value is not None:
                    for index, child in enumerate(value):
                        self.__setitem__(index, child)

                    # Make sure a blank list is serialized
                    if self.contents is None:
                        self._set_contents()

        except (ValueError, TypeError) as e:
            args = e.args[1:]
            e.args = (e.args[0] + '\n    while constructing %s' % type_name(self),) + args
            raise e

    @property
    def contents(self):
        """
        :return:
            A byte string of the DER-encoded contents of the sequence
        """

        if self.children is None:
            return self._contents

        if self._is_mutated():
            self._set_contents()

        return self._contents

    @contents.setter
    def contents(self, value):
        """
        :param value:
            A byte string of the DER-encoded contents of the sequence
        """

        self._contents = value

    def _is_mutated(self):
        """
        :return:
            A boolean - if the sequence or any children (recursively) have been
            mutated
        """

        mutated = self._mutated
        if self.children is not None:
            for child in self.children:
                if isinstance(child, Sequence) or isinstance(child, SequenceOf):
                    mutated = mutated or child._is_mutated()

        return mutated

    def _lazy_child(self, index):
        """
        Builds a child object if the child has only been parsed into a tuple so far
        """

        child = self.children[index]
        if child.__class__ == tuple:
            child = _build(*child)
            self.children[index] = child
        return child

    def _make_value(self, value):
        """
        Constructs a _child_spec value from a native Python data type, or
        an appropriate Asn1Value object

        :param value:
            A native Python value, or some child of Asn1Value

        :return:
            An object of type _child_spec
        """

        if isinstance(value, self._child_spec):
            new_value = value

        elif issubclass(self._child_spec, Any):
            if isinstance(value, Asn1Value):
                new_value = value
            else:
                raise ValueError(unwrap(
                    '''
                    Can not set a native python value to %s where the
                    _child_spec is Any - value must be an instance of Asn1Value
                    ''',
                    type_name(self)
                ))

        elif issubclass(self._child_spec, Choice):
            if not isinstance(value, Asn1Value):
                raise ValueError(unwrap(
                    '''
                    Can not set a native python value to %s where the
                    _child_spec is the choice type %s - value must be an
                    instance of Asn1Value
                    ''',
                    type_name(self),
                    self._child_spec.__name__
                ))
            if not isinstance(value, self._child_spec):
                wrapper = self._child_spec()
                wrapper.validate(value.class_, value.tag, value.contents)
                wrapper._parsed = value
                value = wrapper
            new_value = value

        else:
            return self._child_spec(value=value)

        params = {}
        if self._child_spec.explicit:
            params['explicit'] = self._child_spec.explicit
        if self._child_spec.implicit:
            params['implicit'] = (self._child_spec.class_, self._child_spec.tag)
        return _fix_tagging(new_value, params)

    def __len__(self):
        """
        :return:
            An integer
        """
        # We inline this checks to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        return len(self.children)

    def __getitem__(self, key):
        """
        Allows accessing children via index

        :param key:
            Integer index of child
        """

        # We inline this checks to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        return self._lazy_child(key)

    def __setitem__(self, key, value):
        """
        Allows overriding a child via index

        :param key:
            Integer index of child

        :param value:
            Native python datatype that will be passed to _child_spec to create
            new child object
        """

        # We inline this checks to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        new_value = self._make_value(value)

        # If adding at the end, create a space for the new value
        if key == len(self.children):
            self.children.append(None)
            if self._native is not None:
                self._native.append(None)

        self.children[key] = new_value

        if self._native is not None:
            self._native[key] = self.children[key].native

        self._mutated = True

    def __delitem__(self, key):
        """
        Allows removing a child via index

        :param key:
            Integer index of child
        """

        # We inline this checks to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        self.children.pop(key)
        if self._native is not None:
            self._native.pop(key)

        self._mutated = True

    def __iter__(self):
        """
        :return:
            An iter() of child objects
        """

        # We inline this checks to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        for index in range(0, len(self.children)):
            yield self._lazy_child(index)

    def __contains__(self, item):
        """
        :param item:
            An object of the type cls._child_spec

        :return:
            A boolean if the item is contained in this SequenceOf
        """

        if item is None or item is VOID:
            return False

        if not isinstance(item, self._child_spec):
            raise TypeError(unwrap(
                '''
                Checking membership in %s is only available for instances of
                %s, not %s
                ''',
                type_name(self),
                type_name(self._child_spec),
                type_name(item)
            ))

        for child in self:
            if child == item:
                return True

        return False

    def append(self, value):
        """
        Allows adding a child to the end of the sequence

        :param value:
            Native python datatype that will be passed to _child_spec to create
            new child object
        """

        # We inline this checks to prevent method invocation each time
        if self.children is None:
            self._parse_children()

        self.children.append(self._make_value(value))

        if self._native is not None:
            self._native.append(self.children[-1].native)

        self._mutated = True

    def _set_contents(self, force=False):
        """
        Encodes all child objects into the contents for this object

        :param force:
            Ensure all contents are in DER format instead of possibly using
            cached BER-encoded data
        """

        if self.children is None:
            self._parse_children()

        contents = BytesIO()
        for child in self:
            contents.write(child.dump(force=force))
        self._contents = contents.getvalue()
        self._header = None
        if self._trailer != b'':
            self._trailer = b''

    def _parse_children(self, recurse=False):
        """
        Parses the contents and generates Asn1Value objects based on the
        definitions from _child_spec.

        :param recurse:
            If child objects that are Sequence or SequenceOf objects should
            be recursively parsed

        :raises:
            ValueError - when an error occurs parsing child objects
        """

        try:
            self.children = []
            if self._contents is None:
                return
            contents_length = len(self._contents)
            child_pointer = 0
            while child_pointer < contents_length:
                parts, child_pointer = _parse(self._contents, contents_length, pointer=child_pointer)
                if self._child_spec:
                    child = parts + (self._child_spec,)
                else:
                    child = parts
                if recurse:
                    child = _build(*child)
                    if isinstance(child, (Sequence, SequenceOf)):
                        child._parse_children(recurse=True)
                self.children.append(child)
        except (ValueError, TypeError) as e:
            self.children = None
            args = e.args[1:]
            e.args = (e.args[0] + '\n    while parsing %s' % type_name(self),) + args
            raise e

    def spec(self):
        """
        Determines the spec to use for child values.

        :return:
            A child class of asn1crypto.core.Asn1Value that child values must be
            encoded using
        """

        return self._child_spec

    @property
    def native(self):
        """
        The native Python datatype representation of this value

        :return:
            A list or None. If a list, all child values are recursively
            converted to native representation also.
        """

        if self.contents is None:
            return None

        if self._native is None:
            if self.children is None:
                self._parse_children(recurse=True)
            try:
                self._native = [child.native for child in self]
            except (ValueError, TypeError) as e:
                args = e.args[1:]
                e.args = (e.args[0] + '\n    while parsing %s' % type_name(self),) + args
                raise e
        return self._native

    def _copy(self, other, copy_func):
        """
        Copies the contents of another SequenceOf object to itself

        :param object:
            Another instance of the same class

        :param copy_func:
            An reference of copy.copy() or copy.deepcopy() to use when copying
            lists, dicts and objects
        """

        super(SequenceOf, self)._copy(other, copy_func)
        if self.children is not None:
            self.children = []
            for child in other.children:
                if child.__class__ == tuple:
                    self.children.append(child)
                else:
                    self.children.append(child.copy())

    def debug(self, nest_level=1):
        """
        Show the binary data and parsed data in a tree structure
        """

        if self.children is None:
            self._parse_children()

        prefix = '  ' * nest_level
        _basic_debug(prefix, self)
        for child in self:
            child.debug(nest_level + 1)

    def dump(self, force=False):
        """
        Encodes the value using DER

        :param force:
            If the encoded contents already exist, clear them and regenerate
            to ensure they are in DER format instead of BER format

        :return:
            A byte string of the DER-encoded value
        """

        # If the length is indefinite, force the re-encoding
        if self._header is not None and self._header[-1:] == b'\x80':
            force = True

        if force:
            self._set_contents(force=force)

        return Asn1Value.dump(self) class Set(Sequence):
    """
    Represents a set of fields (unordered) from ASN.1 as a Python object with a
    dict-like interface
    """

    method = 1
    class_ = 0
    tag = 17

    # A dict of 2-element tuples in the form (class_, tag) as keys and integers
    # as values that are the index of the field in _fields
    _field_ids = None

    def _setup(self):
        """
        Generates _field_map, _field_ids and _oid_nums for use in parsing
        """

        cls = self.__class__
        cls._field_map = {}
        cls._field_ids = {}
        cls._precomputed_specs = []
        for index, field in enumerate(cls._fields):
            if len(field) < 3:
                field = field + ({},)
                cls._fields[index] = field
            cls._field_map[field[0]] = index
            cls._field_ids[_build_id_tuple(field[2], field[1])] = index

        if cls._oid_pair is not None:
            cls._oid_nums = (cls._field_map[cls._oid_pair[0]], cls._field_map[cls._oid_pair[1]])

        for index, field in enumerate(cls._fields):
            has_callback = cls._spec_callbacks is not None and field[0] in cls._spec_callbacks
            is_mapped_oid = cls._oid_nums is not None and cls._oid_nums[1] == index
            if has_callback or is_mapped_oid:
                cls._precomputed_specs.append(None)
            else:
                cls._precomputed_specs.append((field[0], field[1], field[1], field[2], None))

    def _parse_children(self, recurse=False):
        """
        Parses the contents and generates Asn1Value objects based on the
        definitions from _fields.

        :param recurse:
            If child objects that are Sequence or SequenceOf objects should
            be recursively parsed

        :raises:
            ValueError - when an error occurs parsing child objects
        """

        cls = self.__class__
        if self._contents is None:
            if self._fields:
                self.children = [VOID] * len(self._fields)
                for index, (_, _, params) in enumerate(self._fields):
                    if 'default' in params:
                        if cls._precomputed_specs[index]:
                            field_name, field_spec, value_spec, field_params, _ = cls._precomputed_specs[index]
                        else:
                            field_name, field_spec, value_spec, field_params, _ = self._determine_spec(index)
                        self.children[index] = self._make_value(field_name, field_spec, value_spec, field_params, None)
            return

        try:
            child_map = {}
            contents_length = len(self.contents)
            child_pointer = 0
            seen_field = 0
            while child_pointer < contents_length:
                parts, child_pointer = _parse(self.contents, contents_length, pointer=child_pointer)

                id_ = (parts[0], parts[2])

                field = self._field_ids.get(id_)
                if field is None:
                    raise ValueError(unwrap(
                        '''
                        Data for field %s (%s class, %s method, tag %s) does
                        not match any of the field definitions
                        ''',
                        seen_field,
                        CLASS_NUM_TO_NAME_MAP.get(parts[0]),
                        METHOD_NUM_TO_NAME_MAP.get(parts[1]),
                        parts[2],
                    ))

                _, field_spec, value_spec, field_params, spec_override = (
                    cls._precomputed_specs[field] or self._determine_spec(field))

                if field_spec is None or (spec_override and issubclass(field_spec, Any)):
                    field_spec = value_spec
                    spec_override = None

                if spec_override:
                    child = parts + (field_spec, field_params, value_spec)
                else:
                    child = parts + (field_spec, field_params)

                if recurse:
                    child = _build(*child)
                    if isinstance(child, (Sequence, SequenceOf)):
                        child._parse_children(recurse=True)

                child_map[field] = child
                seen_field += 1

            total_fields = len(self._fields)

            for index in range(0, total_fields):
                if index in child_map:
                    continue

                name, field_spec, value_spec, field_params, spec_override = (
                    cls._precomputed_specs[index] or self._determine_spec(index))

                if field_spec is None or (spec_override and issubclass(field_spec, Any)):
                    field_spec = value_spec
                    spec_override = None

                missing = False

                if not field_params:
                    missing = True
                elif 'optional' not in field_params and 'default' not in field_params:
                    missing = True
                elif 'optional' in field_params:
                    child_map[index] = VOID
                elif 'default' in field_params:
                    child_map[index] = field_spec(**field_params)

                if missing:
                    raise ValueError(unwrap(
                        '''
                        Missing required field "%s" from %s
                        ''',
                        name,
                        type_name(self)
                    ))

            self.children = []
            for index in range(0, total_fields):
                self.children.append(child_map[index])

        except (ValueError, TypeError) as e:
            args = e.args[1:]
            e.args = (e.args[0] + '\n    while parsing %s' % type_name(self),) + args
            raise e

    def _set_contents(self, force=False):
        """
        Encodes all child objects into the contents for this object.

        This method is overridden because a Set needs to be encoded by
        removing defaulted fields and then sorting the fields by tag.

        :param force:
            Ensure all contents are in DER format instead of possibly using
            cached BER-encoded data
        """

        if self.children is None:
            self._parse_children()

        child_tag_encodings = []
        for index, child in enumerate(self.children):
            child_encoding = child.dump(force=force)

            # Skip encoding defaulted children
            name, spec, field_params = self._fields[index]
            if 'default' in field_params:
                if spec(**field_params).dump() == child_encoding:
                    continue

            child_tag_encodings.append((child.tag, child_encoding))
        child_tag_encodings.sort(key=lambda ct: ct[0])

        self._contents = b''.join([ct[1] for ct in child_tag_encodings])
        self._header = None
        if self._trailer != b'':
            self._trailer = b'' class SetOf(SequenceOf):
    """
    Represents a set (unordered) of a single type of values from ASN.1 as a
    Python object with a list-like interface
    """

    tag = 17

    def _set_contents(self, force=False):
        """
        Encodes all child objects into the contents for this object.

        This method is overridden because a SetOf needs to be encoded by
        sorting the child encodings.

        :param force:
            Ensure all contents are in DER format instead of possibly using
            cached BER-encoded data
        """

        if self.children is None:
            self._parse_children()

        child_encodings = []
        for child in self:
            child_encodings.append(child.dump(force=force))

        self._contents = b''.join(sorted(child_encodings))
        self._header = None
        if self._trailer != b'':
            self._trailer = b'' class TeletexString(AbstractString):
    """
    Represents a teletex string from ASN.1 as a Python unicode string
    """

    tag = 20
    _encoding = 'teletex' class UniversalString(AbstractString):
    """
    Represents a universal string from ASN.1 as a Python unicode string
    """

    tag = 28
    _encoding = 'utf-32-be' class UTCTime(AbstractTime):
    """
    Represents a UTC time from ASN.1 as a timezone aware Python datetime.datetime object
    """

    tag = 23

    # Regular expression for UTCTime as described in X.680 sect. 43 and ISO 8601
    _TIMESTRING_RE = re.compile(r'''
        ^
        # YYMMDD
        (?P<year>\d{2})
        (?P<month>\d{2})
        (?P<day>\d{2})

        # hhmm or hhmmss
        (?P<hour>\d{2})
        (?P<minute>\d{2})
        (?P<second>\d{2})?

        # Matches nothing, needed because GeneralizedTime uses this.
        (?P<fraction>)

        # Z or [-+]hhmm
        (?:
            (?P<zulu>Z)
            |
            (?:
                (?P<dsign>[-+])
                (?P<dhour>\d{2})
                (?P<dminute>\d{2})
            )
        )
        $
    ''', re.X)

    def set(self, value):
        """
        Sets the value of the object

        :param value:
            A unicode string or a datetime.datetime object

        :raises:
            ValueError - when an invalid value is passed
        """

        if isinstance(value, datetime):
            if not value.tzinfo:
                raise ValueError('Must be timezone aware')

            # Convert value to UTC.
            value = value.astimezone(utc_with_dst)

            if not 1950 <= value.year <= 2049:
                raise ValueError('Year of the UTCTime is not in range [1950, 2049], use GeneralizedTime instead')

            value = value.strftime('%y%m%d%H%M%SZ')
            if _PY2:
                value = value.decode('ascii')

        AbstractString.set(self, value)
        # Set it to None and let the class take care of converting the next
        # time that .native is called
        self._native = None

    def _get_datetime(self, parsed):
        """
        Create a datetime object from the parsed time.

        :return:
            An aware datetime.datetime object
        """

        # X.680 only specifies that UTCTime is not using a century.
        # So "18" could as well mean 2118 or 1318.
        # X.509 and CMS specify to use UTCTime for years earlier than 2050.
        # Assume that UTCTime is only used for years [1950, 2049].
        if parsed['year'] < 50:
            parsed['year'] += 2000
        else:
            parsed['year'] += 1900

        return datetime(**parsed) class UTF8String(AbstractString):
    """
    Represents a UTF-8 string from ASN.1 as a Python unicode string
    """

    tag = 12
    _encoding = 'utf-8' class VisibleString(AbstractString):
    """
    Represents a visible string from ASN.1 as a Python unicode string
    """

    tag = 26
    _encoding = 'latin1' VOID = Void() class PublicKeyInfo(Sequence):
    """
    Original Name: SubjectPublicKeyInfo
    Source: https://tools.ietf.org/html/rfc5280#page-17
    """

    _fields = [
        ('algorithm', PublicKeyAlgorithm),
        ('public_key', ParsableOctetBitString),
    ]

    def _public_key_spec(self):
        algorithm = self['algorithm']['algorithm'].native
        return {
            'rsa': RSAPublicKey,
            'rsaes_oaep': RSAPublicKey,
            'rsassa_pss': RSAPublicKey,
            'dsa': Integer,
            # We override the field spec with ECPoint so that users can easily
            # decompose the byte string into the constituent X and Y coords
            'ec': (ECPointBitString, None),
            'dh': Integer,
            # These should be treated as opaque bit strings according
            # to RFC 8410, and need not even be valid ASN.1
            'x25519': (OctetBitString, None),
            'x448': (OctetBitString, None),
            'ed25519': (OctetBitString, None),
            'ed448': (OctetBitString, None),
        }[algorithm]

    _spec_callbacks = {
        'public_key': _public_key_spec
    }

    _algorithm = None
    _bit_size = None
    _fingerprint = None
    _sha1 = None
    _sha256 = None

    @classmethod
    def wrap(cls, public_key, algorithm):
        """
        Wraps a public key in a PublicKeyInfo structure

        :param public_key:
            A byte string or Asn1Value object of the public key

        :param algorithm:
            A unicode string of "rsa"

        :return:
            A PublicKeyInfo object
        """

        if not isinstance(public_key, byte_cls) and not isinstance(public_key, Asn1Value):
            raise TypeError(unwrap(
                '''
                public_key must be a byte string or Asn1Value, not %s
                ''',
                type_name(public_key)
            ))

        if algorithm != 'rsa':
            raise ValueError(unwrap(
                '''
                algorithm must "rsa", not %s
                ''',
                repr(algorithm)
            ))

        algo = PublicKeyAlgorithm()
        algo['algorithm'] = PublicKeyAlgorithmId(algorithm)
        algo['parameters'] = Null()

        container = cls()
        container['algorithm'] = algo
        if isinstance(public_key, Asn1Value):
            public_key = public_key.untag().dump()
        container['public_key'] = ParsableOctetBitString(public_key)

        return container

    def unwrap(self):
        """
        Unwraps an RSA public key into an RSAPublicKey object. Does not support
        DSA or EC public keys since they do not have an unwrapped form.

        :return:
            An RSAPublicKey object
        """

        raise APIException(
            'asn1crypto.keys.PublicKeyInfo().unwrap() has been removed, '
            'please use oscrypto.asymmetric.PublicKey().unwrap() instead')

    @property
    def curve(self):
        """
        Returns information about the curve used for an EC key

        :raises:
            ValueError - when the key is not an EC key

        :return:
            A two-element tuple, with the first element being a unicode string
            of "implicit_ca", "specified" or "named". If the first element is
            "implicit_ca", the second is None. If "specified", the second is
            an OrderedDict that is the native version of SpecifiedECDomain. If
            "named", the second is a unicode string of the curve name.
        """

        if self.algorithm != 'ec':
            raise ValueError(unwrap(
                '''
                Only EC keys have a curve, this key is %s
                ''',
                self.algorithm.upper()
            ))

        params = self['algorithm']['parameters']
        chosen = params.chosen

        if params.name == 'implicit_ca':
            value = None
        else:
            value = chosen.native

        return (params.name, value)

    @property
    def hash_algo(self):
        """
        Returns the name of the family of hash algorithms used to generate a
        DSA key

        :raises:
            ValueError - when the key is not a DSA key

        :return:
            A unicode string of "sha1" or "sha2" or None if no parameters are
            present
        """

        if self.algorithm != 'dsa':
            raise ValueError(unwrap(
                '''
                Only DSA keys are generated using a hash algorithm, this key is
                %s
                ''',
                self.algorithm.upper()
            ))

        parameters = self['algorithm']['parameters']
        if parameters.native is None:
            return None

        byte_len = math.log(parameters['q'].native, 2) / 8

        return 'sha1' if byte_len <= 20 else 'sha2'

    @property
    def algorithm(self):
        """
        :return:
            A unicode string of "rsa", "dsa" or "ec"
        """

        if self._algorithm is None:
            self._algorithm = self['algorithm']['algorithm'].native
        return self._algorithm

    @property
    def bit_size(self):
        """
        :return:
            The bit size of the public key, as an integer
        """

        if self._bit_size is None:
            if self.algorithm == 'ec':
                self._bit_size = int(((len(self['public_key'].native) - 1) / 2) * 8)
            else:
                if self.algorithm == 'rsa':
                    prime = self['public_key'].parsed['modulus'].native
                elif self.algorithm == 'dsa':
                    prime = self['algorithm']['parameters']['p'].native
                self._bit_size = int(math.ceil(math.log(prime, 2)))
                modulus = self._bit_size % 8
                if modulus != 0:
                    self._bit_size += 8 - modulus

        return self._bit_size

    @property
    def byte_size(self):
        """
        :return:
            The byte size of the public key, as an integer
        """

        return int(math.ceil(self.bit_size / 8))

    @property
    def sha1(self):
        """
        :return:
            The SHA1 hash of the DER-encoded bytes of this public key info
        """

        if self._sha1 is None:
            self._sha1 = hashlib.sha1(byte_cls(self['public_key'])).digest()
        return self._sha1

    @property
    def sha256(self):
        """
        :return:
            The SHA-256 hash of the DER-encoded bytes of this public key info
        """

        if self._sha256 is None:
            self._sha256 = hashlib.sha256(byte_cls(self['public_key'])).digest()
        return self._sha256

    @property
    def fingerprint(self):
        """
        Creates a fingerprint that can be compared with a private key to see if
        the two form a pair.

        This fingerprint is not compatible with fingerprints generated by any
        other software.

        :return:
            A byte string that is a sha256 hash of selected components (based
            on the key type)
        """

        raise APIException(
            'asn1crypto.keys.PublicKeyInfo().fingerprint has been removed, '
            'please use oscrypto.asymmetric.PublicKey().fingerprint instead')     def int_to_bytes(value, signed=False, width=None):
    def int_from_bytes(value, signed=False):
        def __init__(self, offset, name=None):
        def __eq__(self, other):
        def __getinitargs__(self):
        def tzname(self, dt):
        def utcoffset(self, dt):
        def dst(self, dt):
    def int_to_bytes(value, signed=False, width=None):
    def int_from_bytes(value, signed=False):
def _format_offset(off):
    def tzname(self, dt):
    def utcoffset(self, dt):
    def dst(self, dt):
def create_timezone(offset):
    def __init__(self, year, month, day):
    def year(self):
    def month(self):
    def day(self):
    def strftime(self, format):
    def isoformat(self):
    def replace(self, year=None, month=None, day=None):
    def __str__(self):
    def __eq__(self, other):
    def __ne__(self, other):
    def _comparison_error(self, other):
    def __cmp__(self, other):
    def __lt__(self, other):
    def __le__(self, other):
    def __gt__(self, other):
    def __ge__(self, other):
    def __init__(self, year, *args, **kwargs):
    def year(self):
    def month(self):
    def day(self):
    def hour(self):
    def minute(self):
    def second(self):
    def microsecond(self):
    def tzinfo(self):
    def utcoffset(self):
    def time(self):
    def date(self):
    def strftime(self, format):
    def isoformat(self, sep='T'):
    def replace(self, year=None, *args, **kwargs):
    def astimezone(self, tz):
    def timestamp(self):
    def __str__(self):
    def __eq__(self, other):
    def __ne__(self, other):
    def _comparison_error(self, other):
    def __cmp__(self, other):
    def __lt__(self, other):
    def __le__(self, other):
    def __gt__(self, other):
    def __ge__(self, other):
    def __add__(self, other):
    def __sub__(self, other):
    def __rsub__(self, other):
    def from_y2k(cls, value):
    class timezone(tzinfo):  # noqa
class _UtcWithDst(tzinfo):
class extended_date(object):
class extended_datetime(object):
    DAYS_IN_400_YEARS = 400 * 365 + 97
    DAYS_IN_2000_YEARS = 5 * DAYS_IN_400_YEARS
from contextlib import contextmanager
from encodings import idna  # noqa
from ._errors import unwrap
from ._iri import iri_to_uri, uri_to_iri
from ._ordereddict import OrderedDict
from ._types import type_name, str_cls, bytes_to_list
from .algos import AlgorithmIdentifier, AnyAlgorithmIdentifier, DigestAlgorithm, SignedDigestAlgorithm
from .core import (
    Any,
    BitString,
    BMPString,
    Boolean,
    Choice,
    Concat,
    Enumerated,
    GeneralizedTime,
    GeneralString,
    IA5String,
    Integer,
    Null,
    NumericString,
    ObjectIdentifier,
    OctetBitString,
    OctetString,
    ParsableOctetString,
    PrintableString,
    Sequence,
    SequenceOf,
    Set,
    SetOf,
    TeletexString,
    UniversalString,
    UTCTime,
    UTF8String,
    VisibleString,
    VOID,
)
from .keys import PublicKeyInfo
from .util import int_to_bytes, int_from_bytes, inet_ntop, inet_pton
import hashlib
import re
import socket
import stringprep
import sys
import unicodedata


class SubjectDirectoryAttribute(Sequence):
    _fields = [
        ('type', SubjectDirectoryAttributeId),
        ('values', Any),
    ]

    _oid_pair = ('type', 'values')
    _oid_specs = {
        'supported_algorithms': SetOfSupportedAlgorithm,
        'tpm_specification': SetOfTPMSpecification,
        'tcg_platform_specification': SetOfTCGPlatformSpecification,
        'tpm_security_assertions': SetOfTPMSecurityAssertions,
        'pda_date_of_birth': SetOfGeneralizedTime,
        'pda_place_of_birth': SetOfDirectoryString,
        'pda_gender': SetOfPrintableString,
        'pda_country_of_citizenship': SetOfPrintableString,
        'pda_country_of_residence': SetOfPrintableString,
    }

    def _values_spec(self):
        type_ = self['type'].native
        if type_ in self._oid_specs:
            return self._oid_specs[type_]
        return SetOf

    _spec_callbacks = {
        'values': _values_spec
    }


class SubjectDirectoryAttributes(SequenceOf):
    _child_spec = SubjectDirectoryAttribute


class ExtensionId(ObjectIdentifier):
    _map = {
        '2.5.29.9': 'subject_directory_attributes',
        '2.5.29.14': 'key_identifier',
        '2.5.29.15': 'key_usage',
        '2.5.29.16': 'private_key_usage_period',
        '2.5.29.17': 'subject_alt_name',
        '2.5.29.18': 'issuer_alt_name',
        '2.5.29.19': 'basic_constraints',
        '2.5.29.30': 'name_constraints',
        '2.5.29.31': 'crl_distribution_points',
        '2.5.29.32': 'certificate_policies',
        '2.5.29.33': 'policy_mappings',
        '2.5.29.35': 'authority_key_identifier',
        '2.5.29.36': 'policy_constraints',
        '2.5.29.37': 'extended_key_usage',
        '2.5.29.46': 'freshest_crl',
        '2.5.29.54': 'inhibit_any_policy',
        '1.3.6.1.5.5.7.1.1': 'authority_information_access',
        '1.3.6.1.5.5.7.1.11': 'subject_information_access',
        # https://tools.ietf.org/html/rfc7633
        '1.3.6.1.5.5.7.1.24': 'tls_feature',
        '1.3.6.1.5.5.7.48.1.5': 'ocsp_no_check',
        '1.2.840.113533.7.65.0': 'entrust_version_extension',
        '2.16.840.1.113730.1.1': 'netscape_certificate_type',
        # https://tools.ietf.org/html/rfc6962.html#page-14
        '1.3.6.1.4.1.11129.2.4.2': 'signed_certificate_timestamp_list',
        # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/3aec3e50-511a-42f9-a5d5-240af503e470
        '1.3.6.1.4.1.311.20.2': 'microsoft_enroll_certtype',
    }


class Extension(Sequence):
    _fields = [
        ('extn_id', ExtensionId),
        ('critical', Boolean, {'default': False}),
        ('extn_value', ParsableOctetString),
    ]

    _oid_pair = ('extn_id', 'extn_value')
    _oid_specs = {
        'subject_directory_attributes': SubjectDirectoryAttributes,
        'key_identifier': OctetString,
        'key_usage': KeyUsage,
        'private_key_usage_period': PrivateKeyUsagePeriod,
        'subject_alt_name': GeneralNames,
        'issuer_alt_name': GeneralNames,
        'basic_constraints': BasicConstraints,
        'name_constraints': NameConstraints,
        'crl_distribution_points': CRLDistributionPoints,
        'certificate_policies': CertificatePolicies,
        'policy_mappings': PolicyMappings,
        'authority_key_identifier': AuthorityKeyIdentifier,
        'policy_constraints': PolicyConstraints,
        'extended_key_usage': ExtKeyUsageSyntax,
        'freshest_crl': CRLDistributionPoints,
        'inhibit_any_policy': Integer,
        'authority_information_access': AuthorityInfoAccessSyntax,
        'subject_information_access': SubjectInfoAccessSyntax,
        'tls_feature': Features,
        'ocsp_no_check': Null,
        'entrust_version_extension': EntrustVersionInfo,
        'netscape_certificate_type': NetscapeCertificateType,
        'signed_certificate_timestamp_list': OctetString,
        # Not UTF8String as Microsofts docs claim, see:
        # https://www.alvestrand.no/objectid/1.3.6.1.4.1.311.20.2.html
        'microsoft_enroll_certtype': BMPString,
    }


class Extensions(SequenceOf):
    _child_spec = Extension


class TbsCertificate(Sequence):
    _fields = [
        ('version', Version, {'explicit': 0, 'default': 'v1'}),
        ('serial_number', Integer),
        ('signature', SignedDigestAlgorithm),
        ('issuer', Name),
        ('validity', Validity),
        ('subject', Name),
        ('subject_public_key_info', PublicKeyInfo),
        ('issuer_unique_id', OctetBitString, {'implicit': 1, 'optional': True}),

        ('subject_unique_id', OctetBitString, {'implicit': 2, 'optional': True}),