o
    "i d                     @   s  d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlZddlm	Z	 ddlm
Z
 dd	lmZ dd
lmZ ddlmZ ddlmZ dZG dd deZG dd deZG dd deZG dd deZeddZ	 G dd deZG dd deZG dd deZdS )z1
This module provides ASN.1 encoder and decoder.
    )absolute_import)division)print_function)unicode_literalsNbytesint)range)str)contextmanager)IntEnumz2.8.0c                   @   s   e Zd Zdd ZdS )HexEnumc                 C   s   dj t| j| j| jdS )Nz<{cls}.{name}: 0x{value:02x}>)clsnamevalue)formattype__name__r   r   self r   D/var/www/html/premium_crap/venv/lib/python3.10/site-packages/asn1.py__repr__    s
   zHexEnum.__repr__N)r   
__module____qualname__r   r   r   r   r   r      s    r   c                   @   sH   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdS )Numbers                  
                           N)r   r   r   BooleanInteger	BitStringOctetStringNullObjectIdentifier
Enumerated
UTF8StringSequenceSetPrintableString	IA5StringUTCTimeGeneralizedTimeUnicodeStringr   r   r   r   r   (   s     r   c                   @   s   e Zd ZdZdZdS )Types    r   N)r   r   r   Constructed	Primitiver   r   r   r   r;   :   s    r;   c                   @   s   e Zd ZdZdZdZdZdS )Classesr   @         N)r   r   r   	UniversalApplicationContextPrivater   r   r   r   r?   ?   s
    r?   Tagz
nr typ clsc                   @   s   e Zd ZdZdS )Errorz,
    ASN.11 encoding or decoding error.
    N)r   r   r   __doc__r   r   r   r   rH   M   s    rH   c                   @   s   e Zd ZdZdd Zdd Zd.ddZd	d
 Zed.ddZ	d/ddZ
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zed!d" Zed#d$ Zed%d& Zed'd( Zed)d* Zed+Zd,d- ZdS )0Encoderz+
    ASN.1 encoder. Uses DER encoding.
    c                 C   s
   d| _ dS )z
        Constructor.
        Nm_stackr   r   r   r   __init__X   s   
zEncoder.__init__c                 C   s   g g| _ dS )z
        This method instructs the encoder to start encoding a new ASN.1
        output. This method may be called at any time to reset the encoder,
        and resets the current output (if any).
        NrK   r   r   r   r   start^   s   zEncoder.startNc                 C   s@   | j du r	td|du rtj}| |tj| | j g  dS )a  
        This method starts the construction of a constructed type.

        Args:
            nr (int): The desired ASN.1 type. Use ``Numbers`` enumeration.

            cls (int): This optional parameter specifies the class
                of the constructed type. The default class to use is the
                universal class. Use ``Classes`` enumeration.

        Returns:
            None

        Raises:
            `Error`
        N,Encoder not initialized. Call start() first.)rL   rH   r?   rC   	_emit_tagr;   r=   appendr   nrr   r   r   r   enterf   s   
zEncoder.enterc                 C   s\   | j du r	tdt| j dkrtdd| j d }| j d= | t| | | dS )z
        This method completes the construction of a constructed type and
        writes the encoded representation to the output buffer.
        NrO   r   Tag stack is empty.    )rL   rH   lenjoin_emit_length_emit)r   r   r   r   r   leave~   s   
zEncoder.leavec                 c   s     |  || dV  |   dS )a  
        This method - context manager calls enter and leave methods,
        for better code mapping.

        Usage:
        ```
        with encoder.construct(asn1.Numbers.Sequence):
            encoder.write(1)
            with encoder.construct(asn1.Numbers.Sequence):
                encoder.write('foo')
                encoder.write('bar')
            encoder.write(2)
        ```
        encoder.output() will result following structure:
        SEQUENCE:
            INTEGER: 1
            SEQUENCE:
                STRING: foo
                STRING: bar
            INTEGER: 2

        Args:
            nr (int): The desired ASN.1 type. Use ``Numbers`` enumeration.

            cls (int): This optional parameter specifies the class
                of the constructed type. The default class to use is the
                universal class. Use ``Classes`` enumeration.

        Returns:
            None

        Raises:
            `Error`

        N)rT   r\   rR   r   r   r   	construct   s   %zEncoder.constructc                 C   s   | j du r	td|du rtj}|du rtj}|tjkr$|du r$td|du rSt|tr1tj	}n"t|t
r:tj}nt|trCtj}nt|trLtj}n|du rStj}| |||}| ||| | t| | | dS )a)  
        This method encodes one ASN.1 tag and writes it to the output buffer.

        Note:
            Normally, ``value`` will be the only parameter to this method.
            In this case Python-ASN1 will autodetect the correct ASN.1 type from
            the type of ``value``, and will output the encoded value based on this
            type.

        Args:
            value (any): The value of the ASN.1 tag to write. Python-ASN1 will
                try to autodetect the correct ASN.1 type from the type of
                ``value``.

            nr (int): If the desired ASN.1 type cannot be autodetected or is
                autodetected wrongly, the ``nr`` parameter can be provided to
                specify the ASN.1 type to be used. Use ``Numbers`` enumeration.

            typ (int): This optional parameter can be used to write constructed
                types to the output by setting it to indicate the constructed
                encoding type. In this case, ``value`` must already be valid ASN.1
                encoded data as plain Python bytes. This is not normally how
                constructed types should be encoded though, see `Encoder.enter()`
                and `Encoder.leave()` for the recommended way of doing this.
                Use ``Types`` enumeration.

            cls (int): This parameter can be used to override the class of the
                ``value``. The default class is the universal class.
                Use ``Classes`` enumeration.

        Returns:
            None

        Raises:
            `Error`
        NrO   zSPlease specify a tag number (nr) when using classes Application, Context or Private)rL   rH   r;   r>   r?   rC   
isinstanceboolr   r,   r	   r-   r   r6   r   r/   r0   _encode_valuerP   rZ   rX   r[   )r   r   rS   typr   r   r   r   write   s.   
%



zEncoder.writec                 C   s<   | j du r	tdt| j dkrtdd| j d }|S )a7  
        This method returns the encoded ASN.1 data as plain Python ``bytes``.
        This method can be called multiple times, also during encoding.
        In the latter case the data that has been encoded so far is
        returned.

        Note:
            It is an error to call this method if the encoder is still
            constructing a constructed type, i.e. if `Encoder.enter()` has been
            called more times that `Encoder.leave()`.

        Returns:
            bytes: The DER encoded ASN.1 data.

        Raises:
            `Error`
        NrO   r   zStack is not empty.rV   r   )rL   rH   rX   rY   )r   outputr   r   r   rc      s   
zEncoder.outputc                 C   s,   |dk r|  ||| dS | ||| dS )zEmit a tag.   N)_emit_tag_short_emit_tag_longr   rS   ra   r   r   r   r   rP     s   zEncoder._emit_tagc                 C   s(   |dk sJ |  t||B |B g dS )zEmit a short (< 31 bytes) tag.rd   Nr[   r   rg   r   r   r   re     s   zEncoder._emit_tag_shortc                 C   sv   t ||B dB g}| | |d@ g}|dL }|r(||d@ dB  |dL }|s|  |D ]
}| t |g q.dS )zEmit a long (>= 31 bytes) tag.rd         rA   N)r   r[   rQ   reverse)r   rS   ra   r   headvaluesvalr   r   r   rf     s   

zEncoder._emit_tag_longc                 C   s$   |dk r|  | dS | | dS )zEmit length octects.rA   N)_emit_length_short_emit_length_longr   lengthr   r   r   rZ   (  s   zEncoder._emit_lengthc                 C   s    |dk sJ |  t|g dS )z*Emit the short length form (< 128 octets).rA   Nrh   rq   r   r   r   ro   /  s   zEncoder._emit_length_shortc                 C   st   g }|r| |d@  |dL }|s|  t|dk sJ tdt|B g}| | |D ]
}| t|g q-dS )z*Emit the long length form (>= 128 octets).      ri   rA   N)rQ   rk   rX   r   r[   )r   rr   rm   rl   rn   r   r   r   rp   4  s   
zEncoder._emit_length_longc                 C   s"   t |tsJ | jd | dS )zEmit raw bytes.rW   N)r^   r   rL   rQ   )r   sr   r   r   r[   B  s   zEncoder._emitc                 C   s   |t jkr|S |tjtjfv r| |S |tjtjtjtj	tj
tjtjfv r+| |S |tjkr5| |S |tjkr?| |S |tjkrH|  S |tjkrR| |S |S )zEncode a value.)r?   rC   r   r-   r2   _encode_integerr/   r6   r3   r7   r:   r8   r9   _encode_octet_stringr.   _encode_bit_stringr,   _encode_booleanr0   _encode_nullr1   _encode_object_identifier)r   r   rS   r   r   r   r   r`   G  s&   










zEncoder._encode_valuec                 C   s   | rt dp	t dS )zEncode a boolean.       r   r   r   r   r   ry   \  s   zEncoder._encode_booleanc                 C   s   | dk r|  } d}d}nd}d}g }| |kr%| | d@  | dL } | |ks| | d@  |rftt|D ]
}d||  ||< q4tt|D ] }||  d7  < || dkrW n|t|d ksaJ d||< qE|rw|t|d  dkrw| d |  t|S )	zEncode an integer.r   TrA   Fri   rs   rt   r   )rQ   r
   rX   rk   r   )r   negativelimitrm   ir   r   r   rv   a  s2   

zEncoder._encode_integerc                 C   s0   t | tst | tsJ t | tr| dS | S )zEncode an octetstring.utf-8)r^   r   r   encoder~   r   r   r   rw     s   

zEncoder._encode_octet_stringc                 C   s   t | tsJ d|  S )z,Encode a bitstring. Assumes no unused bytes.r}   )r^   r   r~   r   r   r   rx     s   zEncoder._encode_bit_stringc                   C   s   t dS )zEncode a Null value.rV   r   r   r   r   r   rz     s   zEncoder._encode_nullz^[0-9]+(\.[0-9]+)+$c                 C   s   | j |s
tdttt|d}|d dkr |d dks&|d dkr*tdd|d  |d  g|dd  }|  g }|D ]}||d	@  |d	kra|d
L }|d|d	@ B  |d	ksPqC|  t	|S )zEncode an object identifier.zIllegal object identifier.r   r   '   r   (   Nri   rj   rA   )
_re_oidmatchrH   listmapr	   splitrk   rQ   r   )r   oidcmpsresultcmp_datar   r   r   r{     s"   $"z!Encoder._encode_object_identifierN)NNN)r   r   r   rI   rM   rN   rT   r\   r   r]   rb   rc   rP   re   rf   rZ   ro   rp   r[   r`   staticmethodry   rv   rw   rx   rz   recompiler   r{   r   r   r   r   rJ   S   s<    

(A


	


rJ   c                   @   s   e Zd ZdZdd Zdd Zdd Zd+d	d
Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zedd Zedd  Zed!d" Zed#d$ Zed%d& Zed'd( Zed)d* ZdS ),DecoderzE
    ASN.1 decoder. Understands BER (and DER which is a subset).
    c                 C   s   d| _ d| _dS )zConstructor.N)rL   m_tagr   r   r   r   rM     s   
zDecoder.__init__c                 C   s,   t |ts	tddt|gg| _d| _dS )a  
        This method instructs the decoder to start decoding the ASN.1 input
        ``data``, which must be a passed in as plain Python bytes.
        This method may be called at any time to start a new decoding job.
        If this method is called while currently decoding another input, that
        decoding context is discarded.

        Note:
            It is not necessary to specify the encoding because the decoder
            assumes the input is in BER or DER format.

        Args:
            data (bytes): ASN.1 input, in BER or DER format, to be decoded.

        Returns:
            None

        Raises:
            `Error`
        zExpecting bytes instance.r   N)r^   r   rH   rL   r   )r   datar   r   r   rN     s   

zDecoder.startc                 C   s8   | j du r	td|  rdS | jdu r|  | _| jS )a  
        This method returns the current ASN.1 tag (i.e. the tag that a
        subsequent `Decoder.read()` call would return) without updating the
        decoding offset. In case no more data is available from the input,
        this method returns ``None`` to signal end-of-file.

        This method is useful if you don't know whether the next tag will be a
        primitive or a constructed tag. Depending on the return value of `peek`,
        you would decide to either issue a `Decoder.read()` in case of a primitive
        type, or an `Decoder.enter()` in case of a constructed type.

        Note:
            Because this method does not advance the current offset in the input,
            calling it multiple times in a row will return the same value for all
            calls.

        Returns:
            `Tag`: The current ASN.1 tag.

        Raises:
            `Error`
        N&No input selected. Call start() first.)rL   rH   _end_of_inputr   	_read_tagr   r   r   r   peek  s   


zDecoder.peekNc                 C   sZ   | j du r	td|  rdS |  }|  }|du r|j}| |j||}d| _||fS )aB  
        This method decodes one ASN.1 tag from the input and returns it as a
        ``(tag, value)`` tuple. ``tag`` is a 3-tuple ``(nr, typ, cls)``,
        while ``value`` is a Python object representing the ASN.1 value.
        The offset in the input is increased so that the next `Decoder.read()`
        call will return the next tag. In case no more data is available from
        the input, this method returns ``None`` to signal end-of-file.

        Returns:
            `Tag`, value: The current ASN.1 tag and its value.

        Raises:
            `Error`
        Nr   )	rL   rH   r   r   _read_lengthrS   _read_valuer   r   )r   tagnrtagrr   r   r   r   r   read  s   
zDecoder.readc                 C   s   |   S )z
        Return True if we are at the end of input.

        Returns:
            bool: True if all input has been decoded, and False otherwise.
        )r   r   r   r   r   eof  s   zDecoder.eofc                 C   sZ   | j du r	td|  }|jtjkrtd|  }| |}| j d|g d| _	dS )a  
        This method enters the constructed type that is at the current
        decoding offset.

        Note:
            It is an error to call `Decoder.enter()` if the to be decoded ASN.1 tag
            is not of a constructed type.

        Returns:
            None
        Nr   z#Cannot enter a non-constructed tag.r   )
rL   rH   r   ra   r;   r=   r   _read_bytesrQ   r   )r   r   rr   
bytes_datar   r   r   rT     s   


zDecoder.enterc                 C   s:   | j du r	tdt| j dkrtd| j d= d| _dS )a  
        This method leaves the last constructed type that was
        `Decoder.enter()`-ed.

        Note:
            It is an error to call `Decoder.leave()` if the current ASN.1 tag
            is not of a constructed type.

        Returns:
            None
        Nr   r   rU   rW   )rL   rH   rX   r   r   r   r   r   r\   '  s   

zDecoder.leavec                 C   s   |   }|d@ }|d@ }|d@ }|dkr)d}	 |   }|d> |d@ B }|d@ s(nqzt|}W n	 ty8   Y nw zt|}W n	 tyH   Y nw |tjkr^zt|}W n	 ty]   Y nw t|||d	S )
z,
        Read a tag from the input.
        rB   r<   rd   r   Trj   ri   rA   )rS   ra   r   )
_read_byter;   
ValueErrorr?   rC   r   rG   )r   byter   ra   rS   r   r   r   r   :  s:   
zDecoder._read_tagc                 C   s|   |   }|d@ r:|d@ }|dkrtd| |}d}|D ]
}|d> t|B }qzt|}W |S  ty9   Y |S w |}|S )z/
        Read a length from the input.
        rA   ri   ASN1 syntax errorr   rt   )r   rH   r   r	   OverflowError)r   r   countr   rr   r   r   r   r   X  s$   

zDecoder._read_lengthc                 C   s   |  |}|tjkr|}|S |tjkr| |}|S |tjtjfv r)| |}|S |tj	kr5| 
|}|S |tjkrA| |}|S |tjkrM| |}|S |tjtjtjtjtjfv rb| |}|S |tjkrn| |}|S |}|S )z.
        Read a value from the input.
        )r   r?   rC   r   r,   _decode_booleanr-   r2   _decode_integerr/   _decode_octet_stringr0   _decode_nullr1   _decode_object_identifierr6   r7   r3   r8   r9   _decode_printable_stringr.   _decode_bitstring)r   r   rS   rr   r   r   r   r   r   r   m  s<   










	



zDecoder._read_valuec                 C   sL   | j d \}}z|| }W n ty   tdw | j d d  d7  < |S )zP
        Return the next input byte, or raise an error on end-of-input.
        rW   Premature end of input.r   r   )rL   
IndexErrorrH   )r   index
input_datar   r   r   r   r     s   zDecoder._read_bytec                 C   sL   | j d \}}||||  }t||krtd| j d d  |7  < |S )z`
        Return the next ``count`` bytes of input. Raise error on
        end-of-input.
        rW   r   r   )rL   rX   rH   )r   r   r   r   r   r   r   r   r     s   zDecoder._read_bytesc                 C   s*   | j d \}}|t|krJ |t|kS )z<
        Return True if we are at the end of input.
        rW   )rL   rX   )r   r   r   r   r   r   r     s   zDecoder._end_of_inputc                 C   s(   t | dkr
td| d dkrdS dS )z)
        Decode a boolean value.
        r   r   r   FTrX   rH   r   r   r   r   r     s
   zDecoder._decode_booleanc                 C   s  dd | D }t |dkr)|d dkr|d d@ s%|d dkr)|d d@ s)td|d d@ }|ritt |D ]
}d||  ||< q7tt |d ddD ]}||  d7  < || dkr^ n|dksdJ d||< qLd}|D ]}|d	> |B }qm|r{| }zt|}W |S  ty   Y |S w )
z*
        Decode an integer value.
        c                 S   s   g | ]}t |qS r   r   ).0br   r   r   
<listcomp>  s    z+Decoder._decode_integer.<locals>.<listcomp>r   r   rs   rA   r   rW   rt   )rX   rH   r
   r	   r   )r   rm   r   r   r   rn   r   r   r   r     s2   <

zDecoder._decode_integerc                 C   s   | S )z)
        Decode an octet string.
        r   r   r   r   r   r     s   zDecoder._decode_octet_stringc                 C   s   t | dkr
tddS )z&
        Decode a Null value.
        r   r   Nr   r   r   r   r   r     s   zDecoder._decode_nullc                 C   s   g }d}t t| D ]'}t| | }|dkr|dkrtd|d> |d@ B }|d@ s1|| d}q
t|dkr<td|d d dkrW|d d |d d g|dd  }nd	|d d
 g|dd  }ttt|}td|S )z.
        Decode an object identifier.
        r   rA   r   rj   ri   r   r   Nr   P   r   )	r
   rX   r	   rH   rQ   r   r   r   rY   )r   r   r   r   r   r   r   r   r     s$   
&z!Decoder._decode_object_identifierc                 C   s
   |  dS )z,
        Decode a printable string.
        r   )decoder   r   r   r   r     s   
z Decoder._decode_printable_stringc                 C   s   t | dkr
td| d }d|  krdks td td|dkr*| dd S t| dd }d|> d }d}tt |D ]}t|| }||? ||> B ||< ||@ }q@t|S )z%
        Decode a bitstring.
        r   r   rj   r   N)rX   rH   	bytearrayr
   r	   r   )r   num_unused_bits	remainingbitmaskremoved_bitsr   r   r   r   r   r     s"   
zDecoder._decode_bitstringr   )r   r   r   rI   rM   rN   r   r   r   rT   r\   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s:    
	






r   )rI   
__future__r   r   r   r   collectionsr   builtinsr   r	   r
   r   
contextlibr   enumr   __version__r   r   r;   r?   
namedtuplerG   	ExceptionrH   objectrJ   r   r   r   r   r   <module>   s2   		  Y