U
    ڲg                     @   s~   d Z ddlZddlZejeef Zeejeef dddZeeeej	e dddZ
eeed	d
dZeeed	ddZdS )z0Functions that load and write PEM-encoded files.    N)
pem_markerreturnc                 C   s,   t | ts| d} d|  d d|  d fS )z:
    Returns the start and end PEM markers, as bytes.
    asciis   -----BEGIN s   -----s	   -----END )
isinstancebytesencode)r    r   +/tmp/pip-unpacked-wheel-1z1vrokf/rsa/pem.py_markers   s
    



r
   )contents	pem_startpem_endr   c                 c   s   d}d}|   D ]^}| }|s"q||krD|r:td| d}d}q|sJq|r^||kr^d} qpd|krhq|V  q|std| |rtd| dS )z7Generator over PEM lines between pem_start and pem_end.FzSeen start marker "%r" twiceT   :zNo PEM start marker "%r" foundzNo PEM end marker "%r" foundN)
splitlinesstrip
ValueError)r   r   r   Zin_pem_partZseen_pem_startliner   r   r	   
_pem_lines&   s0    r   )r   r   r   c                 C   sJ   t | ts| d} t|\}}dd t| ||D }d|}t|S )a  Loads a PEM file.

    :param contents: the contents of the file to interpret
    :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
        when your file has '-----BEGIN RSA PRIVATE KEY-----' and
        '-----END RSA PRIVATE KEY-----' markers.

    :return: the base64-decoded content between the start and end markers.

    @raise ValueError: when the content is invalid, for example when the start
        marker cannot be found.

    r   c                 S   s   g | ]}|qS r   r   ).0r   r   r   r	   
<listcomp>g   s     zload_pem.<locals>.<listcomp>    )r   r   r   r
   r   joinbase64standard_b64decode)r   r   r   r   	pem_linesZpemr   r   r	   load_pemS   s    


r   c                 C   sr   t |\}}t| dd}|g}tdt|dD ]}|||d  }|| q4|| |d d|S )aj  Saves a PEM file.

    :param contents: the contents to encode in PEM format
    :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
        when your file has '-----BEGIN RSA PRIVATE KEY-----' and
        '-----END RSA PRIVATE KEY-----' markers.

    :return: the base64-encoded content between the start and end markers, as bytes.

       
r   r   @   )r
   r   standard_b64encodereplacerangelenappendr   )r   r   r   r   Zb64r   Zblock_startblockr   r   r	   save_pemn   s    

r$   )__doc__r   typingUnionstrr   Z	FlexiTextTupler
   Iteratorr   r   r$   r   r   r   r	   <module>   s   -