o
    Df
t                     @   s   d dl mZ d dlmZ d dlmZmZmZmZ d dl	m
Z
mZmZ d dlmZmZmZ d dlmZmZmZmZmZmZmZmZmZ G dd dZd	d
 ZdS )    )OrderedDict)deepcopy)to_bytesurlsafe_b64encodejson_b64encode
to_unicode)$JWEAlgorithmWithTagAwareKeyAgreementJWESharedHeader	JWEHeader)extract_headerextract_segmentensure_dict)	DecodeErrorMissingAlgorithmErrorUnsupportedAlgorithmErrorMissingEncryptionAlgorithmError#UnsupportedEncryptionAlgorithmError$UnsupportedCompressionAlgorithmErrorInvalidHeaderParameterNameError)InvalidAlgorithmForMultipleRecipientsModeKeyMismatchErrorc                   @   s   e Zd Zeg dZi Zi Zi ZdddZe	dd Z
d ddZd d	d
Zd ddZdddZdddZdddZedd Zdd Zdd Zdd Zdd Zdd ZdS )!JsonWebEncryption)algenczipjkujwkkidx5ux5cx5tzx5t#S256typctycritNc                 C   s   || _ || _d S N)_algorithms_private_headers)self
algorithmsprivate_headers r*   Q/home/ubuntu/webapp/venv/lib/python3.10/site-packages/authlib/jose/rfc7516/jwe.py__init__$   s   
zJsonWebEncryption.__init__c                 C   sn   |r|j dkrtd||jdkr|| j|j< dS |jdkr(|| j|j< dS |jdkr5|| j|j< dS dS )z?Register an algorithm for ``alg`` or ``enc`` or ``zip`` of JWE.JWEzInvalid algorithm for JWE, r   r   r   N)algorithm_type
ValueErroralgorithm_locationALG_REGISTRYnameENC_REGISTRYZIP_REGISTRY)cls	algorithmr*   r*   r+   register_algorithm(   s   


z$JsonWebEncryption.register_algorithmc              	   C   s  |  |}| |}| |}| || | || t|||}|dur*||}t|trK|jdurK|	|||}|d }	|d }
|
|d  n(t|trY|||||}n||||}|d }
|d }d|v rs|
|d  | }t|}t|d}|r|t|}nt|}|||||
\}}t|tr|jdur||||||	|
|}|d }d|t|t|t|t|gS )a  Generate a JWE Compact Serialization.

        The JWE Compact Serialization represents encrypted content as a compact,
        URL-safe string. This string is::

            BASE64URL(UTF8(JWE Protected Header)) || '.' ||
            BASE64URL(JWE Encrypted Key) || '.' ||
            BASE64URL(JWE Initialization Vector) || '.' ||
            BASE64URL(JWE Ciphertext) || '.' ||
            BASE64URL(JWE Authentication Tag)

        Only one recipient is supported by the JWE Compact Serialization and
        it provides no syntax to represent JWE Shared Unprotected Header, JWE
        Per-Recipient Unprotected Header, or JWE AAD values.

        :param protected: A dict of protected header
        :param payload: Payload (bytes or a value convertible to bytes)
        :param key: Public key used to encrypt payload
        :param sender_key: Sender's private key in case
            JWEAlgorithmWithTagAwareKeyAgreement is used
        :return: JWE compact serialization as bytes
        Nepkcekheaderekascii   .)get_header_algget_header_encget_header_zip_validate_sender_key_validate_private_headersprepare_key
isinstancer   key_size!generate_keys_and_prepare_headersupdatewrapgenerate_ivr   r   compressencryptagree_upon_key_and_wrap_cekjoinr   )r'   	protectedpayloadkey
sender_keyr   r   zip_algprepr8   r9   wrappedr;   ivprotected_segmentaadmsg
ciphertexttagr*   r*   r+   serialize_compact6   sJ   





z#JsonWebEncryption.serialize_compactc              
   C   sX  t |ts|g}|stdt|}t|}|d}|du r'dd |D }tt|D ]}|| du r9i ||< d|| vrEi || d< q-|d}t|t|kr_td	t|t|| 
|}	| |}
| |}| ||	 | ||	 |D ]
}| |d |	 q|tt|D ]}t|	|| d || ||< q|dur|	|}|	|
|d	 }d
|v r|d
 }nd}t|dkr|du rt|	jd|v r||d  t |	tr|	jdurg }tt|D ]&}|	|
|| ||}|du r|d
 }||d  || d |d  qnGtt|D ]@}t |	tr*|	|
||| ||}n
|	|
||| |}|du r=|d
 }|d || d< d|v rU|| d |d  q|
 }|jrdt|jnd}|durs|dt| 7 }t|d}|r|t|}nt|}|
 ||||\}}t |	tr|	jdurtt|D ]}|	!|
||| ||| ||}|d || d< qt" }|jrt#t|j|d< |j$r|j$|d< |D ]'}|d s|d= t#t|d |d< t%|& D ]}|dvr||= qq||d< |durt#t||d< t#t||d< t#t||d< t#t||d< |S )a[  Generate a JWE JSON Serialization (in fully general syntax).

        The JWE JSON Serialization represents encrypted content as a JSON
        object.  This representation is neither optimized for compactness nor
        URL safe.

        The following members are defined for use in top-level JSON objects
        used for the fully general JWE JSON Serialization syntax:

        protected
            The "protected" member MUST be present and contain the value
            BASE64URL(UTF8(JWE Protected Header)) when the JWE Protected
            Header value is non-empty; otherwise, it MUST be absent.  These
            Header Parameter values are integrity protected.

        unprotected
            The "unprotected" member MUST be present and contain the value JWE
            Shared Unprotected Header when the JWE Shared Unprotected Header
            value is non-empty; otherwise, it MUST be absent.  This value is
            represented as an unencoded JSON object, rather than as a string.
            These Header Parameter values are not integrity protected.

        iv
            The "iv" member MUST be present and contain the value
            BASE64URL(JWE Initialization Vector) when the JWE Initialization
            Vector value is non-empty; otherwise, it MUST be absent.

        aad
            The "aad" member MUST be present and contain the value
            BASE64URL(JWE AAD)) when the JWE AAD value is non-empty;
            otherwise, it MUST be absent.  A JWE AAD value can be included to
            supply a base64url-encoded value to be integrity protected but not
            encrypted.

        ciphertext
            The "ciphertext" member MUST be present and contain the value
            BASE64URL(JWE Ciphertext).

        tag
            The "tag" member MUST be present and contain the value
            BASE64URL(JWE Authentication Tag) when the JWE Authentication Tag
            value is non-empty; otherwise, it MUST be absent.

        recipients
            The "recipients" member value MUST be an array of JSON objects.
            Each object contains information specific to a single recipient.
            This member MUST be present with exactly one array element per
            recipient, even if some or all of the array element values are the
            empty JSON object "{}" (which can happen when all Header Parameter
            values are shared between all recipients and when no encrypted key
            is used, such as when doing Direct Encryption).

        The following members are defined for use in the JSON objects that
        are elements of the "recipients" array:

        header
            The "header" member MUST be present and contain the value JWE Per-
            Recipient Unprotected Header when the JWE Per-Recipient
            Unprotected Header value is non-empty; otherwise, it MUST be
            absent.  This value is represented as an unencoded JSON object,
            rather than as a string.  These Header Parameter values are not
            integrity protected.

        encrypted_key
            The "encrypted_key" member MUST be present and contain the value
            BASE64URL(JWE Encrypted Key) when the JWE Encrypted Key value is
            non-empty; otherwise, it MUST be absent.

        This implementation assumes that "alg" and "enc" header fields are
        contained in the protected or shared unprotected header.

        :param header_obj: A dict of headers (in addition optionally contains JWE AAD)
        :param payload: Payload (bytes or a value convertible to bytes)
        :param keys: Public keys (or a single public key) used to encrypt payload
        :param sender_key: Sender's private key in case
            JWEAlgorithmWithTagAwareKeyAgreement is used
        :return: JWE JSON serialization (in fully general syntax) as dict

        Example of `header_obj`::

            {
                "protected": {
                    "alg": "ECDH-1PU+A128KW",
                    "enc": "A256CBC-HS512",
                    "apu": "QWxpY2U",
                    "apv": "Qm9iIGFuZCBDaGFybGll"
                },
                "unprotected": {
                    "jku": "https://alice.example.com/keys.jwks"
                },
                "recipients": [
                    {
                        "header": {
                            "kid": "bob-key-2"
                        }
                    },
                    {
                        "header": {
                            "kid": "2021-05-06"
                        }
                    }
                ],
                "aad": b'Authenticate me too.'
            }
        zNo keys have been provided
recipientsNc                 S   s   g | ]}i qS r*   r*   ).0_r*   r*   r+   
<listcomp>	  s    z4JsonWebEncryption.serialize_json.<locals>.<listcomp>r:   rW   zCCount of recipient keys {} does not equal to count of recipients {}r   r9      r8   r;   encrypted_key    r=   r<   rN   unprotected>   r:   ra   rU   rY   rZ   )'rD   listr/   r   r	   	from_dictgetrangelenformatr>   r?   r@   rA   rB   rC   generate_presetr   r2   update_protectedr   rE   rF   appendrG   rH   rI   rN   r   r   r   rJ   rK   rL   r   r   rc   setkeys)r'   
header_objrO   rn   rQ   shared_headerr\   ijwe_aadr   r   rR   	recipientpresetr9   epksrS   rT   rU   rW   rX   rY   rZ   objmemberr*   r*   r+   serialize_json   s   
j








	

	





z JsonWebEncryption.serialize_jsonc                 C   s8   d|v sd|v sd|v r|  ||||S | ||||S )a  Generate a JWE Serialization.

        It will automatically generate a compact or JSON serialization depending
        on `header` argument. If `header` is a dict with "protected",
        "unprotected" and/or "recipients" keys, it will call `serialize_json`,
        otherwise it will call `serialize_compact`.

        :param header: A dict of header(s)
        :param payload: Payload (bytes or a value convertible to bytes)
        :param key: Public key(s) used to encrypt payload
        :param sender_key: Sender's private key in case
            JWEAlgorithmWithTagAwareKeyAgreement is used
        :return: JWE compact serialization as bytes or
            JWE JSON serialization as dict
        rN   rc   r\   )rx   r[   )r'   r:   rO   rP   rQ   r*   r*   r+   	serialize  s   zJsonWebEncryption.serializec                 C   s|  zt |}|d\}}}}}	W n ty   tdw t|t}
t|td}t|td}t|td}t|	td}| |
}| |
}| |
}| 	|| | 
|
| t|trct|dkrc|d }t||
|}|d	urr||}t|tr|jd	ur||||
|||}n||||
||}n||||
|}t |d
}||||||}|r|t |}n|}|r||}|
|dS )a  Extract JWE Compact Serialization.

        :param s: JWE Compact Serialization as bytes
        :param key: Private key used to decrypt payload
            (optionally can be a tuple of kid and essentially key)
        :param decode: Function to decode payload data
        :param sender_key: Sender's public key in case
            JWEAlgorithmWithTagAwareKeyAgreement is used
        :return: dict with `header` and `payload` keys where `header` value is
            a dict containing protected header fields
        r=   zNot enough segmentszencryption keyinitialization vectorrY   authentication tag   r`   Nr<   r:   rO   )r   rsplitr/   r   r   r   r>   r?   r@   rA   rB   rD   tuplerh   rC   r   rE   unwrapdecrypt
decompress)r'   srP   decoderQ   protected_sek_siv_sciphertext_stag_srN   r;   rU   rY   rZ   r   r   rR   r9   rW   rX   rO   r*   r*   r+   deserialize_compact  sD   








z%JsonWebEncryption.deserialize_compactc                    s  t |d}t|}d|v rtt|d tnd|d|d D ]}d|vr.i |d< tt|d td|d< q$d	|v rJtt|d	 td
}nd}tt|d td}tt|d td}tt|d tdt}	| |	 | 	|	| 
|	}
|   | |	  D ]
}| |d   qdttrtdkrd d  du rjdur  fdd} fdd} fdd}fdd}t tr jdur||}n	||}n||}t|dd}d	|v r|dt|d	  7 }t|d}||||}|
r-|
t|}n|}|r6||}D ]}|d sB|d= t| D ]}|dkrR||= qHq8i }r_|d< rf|d< |d< |durs||d	< ||dS )a9  Extract JWE JSON Serialization.

        :param obj: JWE JSON Serialization as dict or str
        :param key: Private key used to decrypt payload
            (optionally can be a tuple of kid and essentially key)
        :param decode: Function to decode payload data
        :param sender_key: Sender's public key in case
            JWEAlgorithmWithTagAwareKeyAgreement is used
        :return: dict with `header` and `payload` keys where `header` value is
            a dict containing `protected`, `unprotected`, `recipients` and/or
            `aad` keys
        r-   rN   Nrc   r\   r:   ra   zencrypted keyrW   zJWE AADrU   rz   rY   rZ   r{   r|   r   r`   c                    s     | |S r$   r   r;   r:   )r   r   rP   rQ   rZ   r*   r+   _unwrap_with_sender_key_and_tag#  s   zKJsonWebEncryption.deserialize_json.<locals>._unwrap_with_sender_key_and_tagc                    s     | |S r$   r   r   )r   r   rP   rQ   r*   r+   '_unwrap_with_sender_key_and_without_tag&  s   zSJsonWebEncryption.deserialize_json.<locals>._unwrap_with_sender_key_and_without_tagc                    s     | |S r$   r   r   )r   r   rP   r*   r+   "_unwrap_without_sender_key_and_tag)  s   zNJsonWebEncryption.deserialize_json.<locals>._unwrap_without_sender_key_and_tagc                    s    d ur#D ]}|d  d kr"t|d }| |d |  S qd }D ](}t|d }z
| |d |W   S  tyO } z|}W Y d }~q'd }~ww |d u rWt |)Nr:   r   ra   )rf   r
   	Exceptionr   )unwrap_funcrs   r:   errore)r   rN   r\   rc   r*   r+   _unwrap_for_matching_recipient,  s$   zJJsonWebEncryption.deserialize_json.<locals>._unwrap_for_matching_recipient r=   r<   r}   )r   r   r   r   r   rf   r   r	   r>   r?   r@   rA   rB   rD   r   rh   rC   r   r   rE   r   r   rm   rn   )r'   rv   rP   r   rQ   rs   rr   rU   rY   rp   rR   r   r   r   r   r9   rW   rX   rO   rw   r:   r*   )	r   r   rP   r   rN   r\   rQ   rZ   rc   r+   deserialize_json  s   

















z"JsonWebEncryption.deserialize_jsonc                 C   sV   t |tr| ||||S t|}|dr#|dr#| ||||S | ||||S )a%  Extract a JWE Serialization.

        It supports both compact and JSON serialization.

        :param obj: JWE compact serialization as bytes or
            JWE JSON serialization as dict or str
        :param key: Private key used to decrypt payload
            (optionally can be a tuple of kid and essentially key)
        :param decode: Function to decode payload data
        :param sender_key: Sender's public key in case
            JWEAlgorithmWithTagAwareKeyAgreement is used
        :return: dict with `header` and `payload` keys
           {   })rD   dictr   r   
startswithendswithr   )r'   rv   rP   r   rQ   r*   r*   r+   deserializes  s   
zJsonWebEncryption.deserializec                 C   s
   t | dS )zParse JWE JSON Serialization.

        :param obj: JWE JSON Serialization as str or dict
        :return: Parsed JWE JSON Serialization as dict if `obj` is an str,
            or `obj` as is if `obj` is already a dict
        r-   )r   )rv   r*   r*   r+   
parse_json  s   
zJsonWebEncryption.parse_jsonc                 C   J   d|vrt  |d }| jd ur|| jvrt || jvr t | j| S )Nr   )r   r%   r   r1   )r'   r:   r   r*   r*   r+   r>     s   

z JsonWebEncryption.get_header_algc                 C   r   )Nr   )r   r%   r   r3   )r'   r:   r   r*   r*   r+   r?     s   

z JsonWebEncryption.get_header_encc                 C   sH   d|v r"|d }| j d ur|| j vrt || jvrt | j| S d S )Nr   )r%   r   r4   )r'   r:   zr*   r*   r+   r@     s   

z JsonWebEncryption.get_header_zipc                 C   sB   t |tr|d u rtd|jd S |d urtd|jd S )NzD{} algorithm requires sender_key but passed sender_key value is NonezL{} algorithm does not use sender_key but passed sender_key value is not None)rD   r   r/   ri   r2   )r'   rQ   r   r*   r*   r+   rA     s   
z&JsonWebEncryption._validate_sender_keyc                 C   sT   | j d u rd S | j }|| j }|jr||j}|D ]
}||vr't|qd S r$   )r&   !REGISTERED_HEADER_PARAMETER_NAMEScopyunionEXTRA_HEADERSr   )r'   r:   r   nameskr*   r*   r+   rB     s   

z+JsonWebEncryption._validate_private_headers)NNr$   )__name__
__module____qualname__	frozensetr   r1   r3   r4   r,   classmethodr7   r[   rx   ry   r   r   r   staticmethodr   r>   r?   r@   rA   rB   r*   r*   r*   r+   r      s.    



] 
w

B 

	
	
r   c                 C   s6   t |r
||d }n|d u rd|v r|d }| |S )Nr   )callablerC   )r   r:   rP   r*   r*   r+   rC     s
   
rC   N)collectionsr   r   r   authlib.common.encodingr   r   r   r   authlib.jose.rfc7516.modelsr   r	   r
   authlib.jose.utilr   r   r   authlib.jose.errorsr   r   r   r   r   r   r   r   r   r   rC   r*   r*   r*   r+   <module>   s    ,     ;