ó
Ÿ^Yc           @   sG   d  Z  d d l Z d d l m Z m Z d   Z d   Z d   Z d S(   s0   Functions that load and write PEM-encoded files.iÿÿÿÿN(   t   bt   is_bytesc         C   s<   t  |   r |  j d  }  n  t d |   t d |   f S(   s/   
    Returns the start and end PEM markers
    s   utf-8s   -----BEGIN %s-----s   -----END %s-----(   R   t   decodeR    (   t
   pem_marker(    (    s$   /tmp/pip-build-kpPAdC/rsa/rsa/pem.pyt   _markers   s    c         C   s=  t  |   s |  j d  }  n  t |  \ } } g  } t } xª |  j   D] } | j   } | sg qI n  | | k r | r t d |   n  t } qI n  | s€ qI n  | rÀ | | k rÀ t } Pn  t d  | k rØ qI n  | j	 |  qI W| st d |   n  | rt d |   n  t d  j
 |  } t j |  S(   sÑ  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.

    t   asciis   Seen start marker "%s" twicet   :s   No PEM start marker "%s" founds   No PEM end marker "%s" foundt    (   R   t   encodeR   t   Falset
   splitlinest   stript
   ValueErrort   TrueR    t   appendt   joint   base64t   standard_b64decode(   t   contentsR   t	   pem_startt   pem_endt	   pem_linest   in_pem_partt   linet   pem(    (    s$   /tmp/pip-build-kpPAdC/rsa/rsa/pem.pyt   load_pem#   s8    c         C   s¶   t  |  \ } } t j |   j t d  t d   } | g } x> t d t |  d  D]$ } | | | d !} | j |  q[ W| j |  | j t d   t d  j |  S(   s`  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.

    s   
R   i    i@   (	   R   R   t   standard_b64encodet   replaceR    t   ranget   lenR   R   (   R   R   R   R   t   b64R   t   block_startt   block(    (    s$   /tmp/pip-build-kpPAdC/rsa/rsa/pem.pyt   save_peme   s    '	(   t   __doc__R   t   rsa._compatR    R   R   R   R!   (    (    (    s$   /tmp/pip-build-kpPAdC/rsa/rsa/pem.pyt   <module>   s
   		B