o
    <ic                     @   s\  d dl Z d dlmZ d dlmZmZ d dlmZmZ d dlmZm	Z	 d dlm
Z
mZ d dlmZ d dlmZ d	Zd
ZeddddeddddeddddeddddeddddeddddeddddeddddeddddeddddeddddeddddedddddZ	 g dZ	 G dd deZejZejZejZejZG dd dZdS )     N)common)JWExceptionJWKeyNotFound)JWSEHeaderParameterJWSEHeaderRegistry)base64url_decodebase64url_encode)json_decodejson_encode)JWA)JWKSeti   i  @	AlgorithmFTzEncryption AlgorithmzCompression AlgorithmzJWK Set URLzJSON Web KeyzKey IDz	X.509 URLzX.509 Certificate Chainz"X.509 Certificate SHA-1 Thumbprintz$X.509 Certificate SHA-256 ThumbprintTypezContent TypeCritical)algenczipjkujwkkidx5ux5cx5tzx5t#S256typctycrit)zRSA-OAEPzRSA-OAEP-256A128KWA192KWA256KWdirzECDH-ESzECDH-ES+A128KWzECDH-ES+A192KWzECDH-ES+A256KW	A128GCMKW	A192GCMKW	A256GCMKWzPBES2-HS256+A128KWzPBES2-HS384+A192KWzPBES2-HS512+A256KWzA128CBC-HS256zA192CBC-HS384zA256CBC-HS512A128GCMA192GCMA256GCMc                       s"   e Zd ZdZd fdd	Z  ZS )InvalidJWEDatazvInvalid JWE Object.

    This exception is raised when the JWE Object is invalid and/or
    improperly formatted.
    Nc                    s:   d }|r|}nd}|r|dt | 7 }tt| | d S )Nz!Unknown Data Verification Failurez {%s})strsuperr&   __init__)selfmessage	exceptionmsg	__class__ K/root/parts/websockify/install/lib/python3.10/site-packages/jwcrypto/jwe.pyr)   <   s   zInvalidJWEData.__init__)NN)__name__
__module____qualname____doc__r)   __classcell__r0   r0   r.   r1   r&   5   s    r&   c                   @   s   e Zd ZdZ			d1ddZdd Zdd	 Zed
d Zej	dd Zdd Z
d2ddZdd Zdd Zd2ddZd3ddZdd Zdd ZefddZd4d!d"Zd2d#d$Zed%d& Zed'd( Zed)d* Zd+d, Zd-d. Zd/d0 ZdS )5JWEzGJSON Web Encryption object

    This object represent a JWE token.
    NTc
           
      C   s   d| _ i | _d| _tt| _|	| _|r| j| |dur,t|t	r&|| _n|
d| _d| _d| _|r9|| jd< |rNt|trEt|}nt| || jd< |rct|trZt|}nt| || jd< |rh|| _ |rs| j||d dS |rytddS )a  Creates a JWE token.

        :param plaintext(bytes): An arbitrary plaintext to be encrypted.
        :param protected: A JSON string with the protected header.
        :param unprotected: A JSON string with the shared unprotected header.
        :param aad(bytes): Arbitrary additional authenticated data
        :param algs: An optional list of allowed algorithms
        :param recipient: An optional, default recipient key
        :param header: An optional header for the default recipient
        :param header_registry: Optional additions to the header registry
        :param flattened: Use flattened serialization syntax (default True)
        Nutf-8aad	protectedunprotected)headerz-Header is allowed only with default recipient)_allowed_algsobjects	plaintextr   JWEHeaderRegistryheader_registry	flattenedupdate
isinstancebytesencodecek
decryptlogdictr
   r	   add_recipient
ValueError)
r*   r?   r:   r;   r9   algs	recipientr<   rA   rB   r0   r0   r1   r)   T   s@   








zJWE.__init__c                 C   $   | j pt}||vrtdt|S NzAlgorithm not allowed)r=   default_allowed_algsInvalidJWEOperationr   keymgmt_algr*   nameallowedr0   r0   r1   _jwa_keymgmt      

zJWE._jwa_keymgmtc                 C   rN   rO   )r=   rP   rQ   r   encryption_algrS   r0   r0   r1   _jwa_enc   rW   zJWE._jwa_encc                 C   s   | j r| j S tS )zAllowed algorithms.

        The list of allowed algorithms.
        Can be changed by setting a list of algorithm names.
        )r=   rP   r*   r0   r0   r1   allowed_algs   s   zJWE.allowed_algsc                 C   s   t |ts	td|| _d S )NzAllowed Algs must be a list)rD   list	TypeErrorr=   )r*   rL   r0   r0   r1   r[      s   

c                 C   s4   t | D ]}||v rtd| q|| |S )NzDuplicate header: "%s")r\   keysr&   rC   )r*   h1h2kr0   r0   r1   _merge_headers   s   
zJWE._merge_headersc                 C   sh   i }d| j v rt| j d }| ||}d| j v r&t| j d }| ||}|r2t|}| ||}|S )Nr:   r;   )r>   r	   rb   )r*   r<   jhphuhrhr0   r0   r1   _get_jose_header   s   

zJWE._get_jose_headerc                 C   sT   | dd }|d u rtd| |}| dd }|d u r!td| |}||fS )Nr   zMissing "alg" from headersr   zMissing "enc" from headers)getr&   rV   rY   )r*   rc   algnamer   encnamer   r0   r0   r1   _get_alg_enc_from_headers   s   

zJWE._get_alg_enc_from_headersc           
      C   s   t | jdd}d| jv r|dt | jd  7 }|d}|dd }|dkr3t| jdd	 }n|d u r;| j}ntd
|| j	||\}}}	|| jd< || jd< |	| jd< d S )Nr:    r9   .r8   r   DEF   Unknown compressioniv
ciphertexttag)
r   r>   rh   rF   zlibcompressr?   rK   encryptrG   )
r*   r   r   rc   r9   rv   datarr   rs   rt   r0   r0   r1   _encrypt   s   



zJWE._encryptc                 C   s  | j du r	tdt| j tstdt|trt|}| |}| |\}}i }|r0||d< |||j	| j
|}|d | _
d|v rI|d |d< d|v rct|dd}| ||d }	t|	|d< d	| jvro| ||| d
| jv r~| jd
 | dS | jrd| jv sd| jv rg | jd
< i }
d| jv r| jd|
d< d| jv r| jd|
d< | jd
 |
 | jd
 | dS | j| dS |g| jd
< dS )a  Encrypt the plaintext with the given key.

        :param key: A JWK key or password of appropriate type for the 'alg'
         provided in the JOSE Headers.
        :param header: A JSON string representing the per-recipient header.

        :raises ValueError: if the plaintext is missing or not of type bytes.
        :raises ValueError: if the compression type is unknown.
        :raises InvalidJWAAlgorithm: if the 'alg' provided in the JOSE
         headers is missing or unknown, or otherwise not implemented.
        NzMissing plaintextzPlaintext must be 'bytes'r<   rG   ekencrypted_keyz{}rs   
recipients)r?   rK   rD   rE   rI   r
   rg   rk   wrapwrap_key_sizerG   r	   rh   rb   r>   ry   appendrB   poprC   )r*   keyr<   rc   r   r   recwrappedhnhnr0   r0   r1   rJ      sF   








zJWE.add_recipientFc              	   C   sz  d| j vr	td|rdD ]}|| j v rtd| qd| j vr$tdt| j d }dD ]}||vr9td| q-d	| j v rTt| j d	 d
krLtd| j d	 d }n| j }d|v rt|d }t| j d }| ||}t|| j d< |  }| |\}	}
| |	|
| |d= d	t
| j d t
|ddt
| j d t
| j d t
| j d gS | j }t
|d t
|d t
| j d d}
d|v rt
|d |
d< d|v rt|d |
d< d|v rt
|d |
d< d	|v rg |
d	< |d	 D ]%}i }d|v rt
|d |d< d|v rt|d |d< |
d	 | qt|
S d|v r,t
|d |
d< d|v r9t|d |
d< t|
S )a  Serializes the object into a JWE token.

        :param compact(boolean): if True generates the compact
         representation, otherwise generates a standard JSON format.

        :raises InvalidJWEOperation: if the object cannot be serialized
         with the compact representation and `compact` is True.
        :raises InvalidJWEOperation: if no recipients have been added
         to the object.

        :return: A json formatted string or a compact representation string
        :rtype: `str`
        rs   No available ciphertext)r9   r;   z9Can't use compact encoding when the '%s' parameter is setr:   z4Can't use compact encoding without protected headers)r   r   z@Can't use compact encoding, '%s' must be in the protected headerr|      zInvalid number of recipientsr   r<   rm   r{   rl   rr   rt   )rs   rr   rt   r;   r9   )r>   rQ   r	   lenrb   r
   rg   rk   ry   joinr   rh   r   )r*   compactinvalidrd   requiredr   r   nphrc   r   r   objer0   r0   r1   	serialize  s   












zJWE.serializec                 C   s<   |D ]}|| j vrtd| | j | jstd| qd S )NzUnknown critical header: "%s"z!Unsupported critical header: "%s")rA   r&   	supported)r*   r   ra   r0   r0   r1   _check_critj  s   
zJWE._check_critc
                 C   s:   | ||j||}
||
||||	}| jd |
| _|S )NSuccess)unwrapr~   decryptrH   r   rG   )r*   r   r   r   enckeyr<   r9   rr   rs   rt   rG   rx   r0   r0   r1   _unwrap_decrypts  s
   zJWE._unwrap_decryptc                 C   sv  |  |dd }| |di  |D ]}|| jv r&| j|| s&tdq| |dd }| |dd }t| j	dd}d| j	v rR|d	t| j	d  7 }|
d
}t|tr|}	d| jv ry|| jd }
|
swtd| jd |
}	|	D ]K}z#| ||||dd||| j	d | j	d | j	d 	}| jd W  n& ty } z|d| }| jd|t| W Y d }~q{d }~ww d| jvrtdn| ||||dd||| j	d | j	d | j	d 	}|dd }|dkr-t|tkrtddt d tjtj d}|||| _|js|js+d | _tdd| d d S |d u r7|| _d S t d)Nr<   r   zFailed header checkr   r   r:   rl   r9   rm   r8   r   zKey ID {} not in key setr{       rr   rs   rt   r   zKey [{}] failed: [{}]zNo working key found in key setr   rn   z+Compressed data exceeds maximum allowedsizez ())wbitsz2Compressed data exceeds maximum allowedoutput sizerq   )!rg   rh   r   rA   check_headerr&   rV   rY   r   r>   rF   rD   r   jose_headerget_keysr   formatr   rH   r   	Exception
thumbprintreprr   default_max_compressed_sizeru   decompressobj	MAX_WBITS
decompressr?   unconsumed_taileofrK   )r*   r   ppemax_plaintextrc   hdrr   r   r9   r^   kid_keysra   rx   r   keyidrv   dor0   r0   r1   _decrypt|  s   















zJWE._decryptr   c                 C   s*  d| _ |dkr	t}d| jvrtdg | _d}d| jv rR| jd D ]/}z
| j|||d W q! tyP } zt|tr<d}| j	d	t
|  W Y d}~q!d}~ww n/z| j|| j|d W n# ty } zt|trld}| j	d	t
|  W Y d}~nd}~ww | j s|rtd
tdt
| j dS )a9  Decrypt a JWE token.

        :param key: The (:class:`jwcrypto.jwk.JWK`) decryption key.
        :param key: A (:class:`jwcrypto.jwk.JWK`) decryption key,
         or a (:class:`jwcrypto.jwk.JWKSet`) that contains a key indexed
         by the 'kid' header or (deprecated) a string containing a password.
        :param max_plaintext: Maximum plaintext size allowed, 0 means
         the library default applies. Application writers are recommended
         to set a limit here if they know what is the max plaintext size
         for their application.

        :raises InvalidJWEOperation: if the key is not a JWK object.
        :raises InvalidJWEData: if the ciphertext can't be decrypted or
         the object is otherwise malformed.
        :raises JWKeyNotFound: if key is a JWKSet and the key is not found.
        Nr   rs   r   Fr|   )r   TzFailed: [%s]zKey Not found in JWKSetz%No recipient matched the provided key)r?   default_max_plaintext_sizer>   rQ   rH   r   r   rD   r   r   r   r&   )r*   r   r   
missingkeyr   r   r0   r0   r1   r     sB   


 
 zJWE.decryptc           
   
   C   s6  i | _ d| _d| _i }zzt|}t|d |d< t|d |d< t|d |d< d|v r:t|d }|d|d< d|v rFt|d |d< d|v rRt|d |d< d	|v rg |d	< |d	 D ]#}i }d
|v rnt|d
 |d
< d|v rzt|d |d< |d	 | q^nd
|v rt|d
 |d
< d|v rt|d |d< W nX ty } zL|	d}t
|dkrt |t|d }|d|d< t|d }	|	dkrt|d |d
< t|d |d< t|d |d< t|d |d< W Y d}~nd}~ww || _ W n ty } ztdt||d}~ww |r| | dS dS )a  Deserialize a JWE token.

        NOTE: Destroys any current status and tries to import the raw
        JWE provided.

        If a key is provided a decryption step will be attempted after
        the object is successfully deserialized.

        :param raw_jwe: a 'raw' JWE token (JSON Encoded or Compact
         notation) string.
        :param key: A (:class:`jwcrypto.jwk.JWK`) decryption key,
         or a (:class:`jwcrypto.jwk.JWKSet`) that contains a key indexed
         by the 'kid' header or (deprecated) a string containing a password
         (optional).

        :raises InvalidJWEData: if the raw object is an invalid JWE token.
        :raises InvalidJWEOperation: if the decryption fails.
        Nrr   rs   rt   r:   r8   r;   r9   r|   r{   r<   rm      r   r   r   ro         zInvalid format)r>   r?   rG   r	   r   decoder
   r   rK   splitr   r&   r   r   r   )
r*   raw_jwer   odjwepr   r   rx   ekeyr0   r0   r1   deserialize  sp   
	


zJWE.deserializec                 C   s   | j std| j S )NzPlaintext not available)r?   rQ   rZ   r0   r0   r1   payload?  s   zJWE.payloadc                 C   s*   |  | jd}t|dkrtd|S )Nr<   r   zJOSE Header not available)rg   r>   rh   r   rQ   )r*   rc   r0   r0   r1   r   E  s   zJWE.jose_headerc                 C   s   |  }| | |S )a  Creates a JWE object from a serialized JWE token.

        :param token: A string with the json or compat representation
         of the token.

        :raises InvalidJWEData: if the raw object is an invalid JWE token.

        :return: A JWE token
        :rtype: JWE
        )r   )clstokenr   r0   r0   r1   from_jose_tokenL  s   
zJWE.from_jose_tokenc                 C   sh   t |tsdS z	|  | kW S  ty3   d| ji}|| j d|ji}||j ||k Y S w )NFr?   )rD   r7   r   r   r?   rC   r>   )r*   otherdata1data2r0   r0   r1   __eq__]  s   


z
JWE.__eq__c                 C   s&   z|   W S  ty   |   Y S w N)r   r   __repr__rZ   r0   r0   r1   __str__i  s
   
zJWE.__str__c              	   C   s   z	d|    dW S  tyG   t| j}| jd}| jd}| jd}| j}d| dd| d d	| d d
| d| d  Y S w )NzJWE.from_json_token("z")r:   r;   r9   zJWE(plaintext=z, z
protected=zunprotected=zaad=z, algs=r   )r   r   r   r?   r>   rh   r=   )r*   r?   r:   r;   r9   rL   r0   r0   r1   r   o  s    



zJWE.__repr__)	NNNNNNNNTr   )F)r   )r2   r3   r4   r5   r)   rV   rY   propertyr[   setterrb   rg   rk   ry   rJ   r   r   r   r   r   r   r   r   r   classmethodr   r   r   r   r0   r0   r0   r1   r7   N   s@    
3




:X		
F
1L


r7   )ru   jwcryptor   jwcrypto.commonr   r   r   r   r   r   r	   r
   jwcrypto.jwar   jwcrypto.jwkr   r   r   r@   rP   r&   InvalidCEKeyLengthInvalidJWEKeyLengthInvalidJWEKeyTyperQ   r7   r0   r0   r0   r1   <module>   sJ   