
    ʏe]                        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  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e      Zej&                  Zej(                  Zej*                  Zej,                  Z G d d      Zy)    N)common)JWExceptionJWKeyNotFound)JWSEHeaderParameterJWSEHeaderRegistry)base64url_decodebase64url_encode)json_decodejson_encode)JWA)JWKSet	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                   $     e Zd ZdZd fd	Z xZS )InvalidJWEDatazvInvalid JWE Object.

    This exception is raised when the JWE Object is invalid and/or
    improperly formatted.
    c                 d    d }|r|}nd}|r|dt        |      z  z  }t        t        |   |       y )Nz!Unknown Data Verification Failurez {%s})strsuperr(   __init__)selfmessage	exceptionmsg	__class__s       ./usr/lib/python3/dist-packages/jwcrypto/jwe.pyr,   zInvalidJWEData.__init__8   s:    C5C7S^++Cnd,S1    )NN)__name__
__module____qualname____doc__r,   __classcell__)r1   s   @r2   r(   r(   1   s    2 2r3   r(   c                       e Zd ZdZ	 	 	 ddZd Zd Zed        Zej                  d        Zd Z
dd	Zd
 Zd ZddZddZd Zd Zd Zd ZddZed        Zed        Zed        Zd Zd Zd Zy)JWEzGJSON Web Encryption object

    This object represent a JWE token.
    Nc	                 f   d| _         i | _        d| _        t        t              | _        |r| j
                  j                  |       |.t        |t              r|| _        n|j                  d      | _        d| _
        d| _        |r|| j                  d<   |r6t        |t              rt        |      }nt        |       || j                  d<   |r6t        |t              rt        |      }nt        |       || j                  d<   |r|| _         |r| j                  ||       y|rt!        d      y)aB  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
        Nutf-8aad	protectedunprotected)headerz-Header is allowed only with default recipient)_allowed_algsobjects	plaintextr   JWEHeaderRegistryheader_registryupdate
isinstancebytesencodecek
decryptlogdictr   r
   add_recipient
ValueError)	r-   rC   r>   r?   r=   algs	recipientr@   rE   s	            r2   r,   zJWE.__init__P   s    "12CD  ''8 )U+!*!*!1!1'!:"%DLL)T*'	2	I&(1DLL%+t,)+6K(*5DLL'!%Dy8LMM r3   c                 r    | j                   xs t        }||vrt        d      t        j                  |      S NzAlgorithm not allowed)rA   default_allowed_algsInvalidJWEOperationr   keymgmt_algr-   namealloweds      r2   _jwa_keymgmtzJWE._jwa_keymgmt   s6    $$<(<w%&=>>t$$r3   c                 r    | j                   xs t        }||vrt        d      t        j                  |      S rR   )rA   rS   rT   r   encryption_algrV   s      r2   _jwa_enczJWE._jwa_enc   s8    $$<(<w%&=>>!!$''r3   c                 >    | j                   r| j                   S t        S )zAllowed algorithms.

        The list of allowed algorithms.
        Can be changed by setting a list of algorithm names.
        )rA   rS   r-   s    r2   allowed_algszJWE.allowed_algs   s     %%%''r3   c                 H    t        |t              st        d      || _        y )NzAllowed Algs must be a list)rG   list	TypeErrorrA   )r-   rO   s     r2   r_   zJWE.allowed_algs   s     $%9::!r3   c                     t        |j                               D ]  }||v st        d|z         |j                  |       |S )NzDuplicate header: "%s")ra   keysr(   rF   )r-   h1h2ks       r2   _merge_headerszJWE._merge_headers   sG    bggi 	CABw$%=%ABB	C 			"	r3   c                 (   i }d| j                   v r*t        | j                   d         }| j                  ||      }d| j                   v r*t        | j                   d         }| j                  ||      }|rt        |      }| j                  ||      }|S )Nr>   r?   )rB   r
   rh   )r-   r@   jhphuhrhs         r2   _get_jose_headerzJWE._get_jose_header   s    $,,&T\\+67B$$R,BDLL(T\\-89B$$R,BV$B$$R,B	r3   c                     |j                  dd       }|t        d      | j                  |      }|j                  dd       }|t        d      | j                  |      }||fS )Nr   zMissing "alg" from headersr   zMissing "enc" from headers)getr(   rY   r\   )r-   rj   algnamer   encnamer   s         r2   _get_alg_enc_from_headerszJWE._get_alg_enc_from_headers   sk    &&%? !=>>(&&%? !=>>mmG$Cxr3   c                    t        | j                  j                  dd            }d| j                  v r|dt        | j                  d         z   z  }|j                  d      }|j                  dd       }|dk(  r#t	        j
                  | j                        dd	 }n|| j                  }nt        d
      |j                  | j                  ||      \  }}}	|| j                  d<   || j                  d<   |	| j                  d<   y )Nr>    r=   .r<   r   DEF   Unknown compressioniv
ciphertexttag)
r	   rB   rp   rI   zlibcompressrC   rN   encryptrJ   )
r-   r   r   rj   r=   r   datar{   r|   r}   s
             r2   _encryptzJWE._encrypt   s    t||//R@ADLL 3)$,,u*=>>>Cjj!66%&u==026D>>D233!kk$((C>JT%/\"!Ur3   c                 d   | j                   t        d      t        | j                   t              st        d      t        |t              rt        |      }| j                  |      }| j                  |      \  }}i }|r||d<   |j                  ||j                  | j                  |      }|d   | _
        d|v r|d   |d<   d|v r>t        |j                  dd            }| j                  ||d         }	t        |	      |d<   d	| j                  vr| j                  |||       d
| j                  v r| j                  d
   j!                  |       yd| j                  v sd| j                  v rg | j                  d
<   i }
d| j                  v r| j                  j#                  d      |
d<   d| j                  v r| j                  j#                  d      |
d<   | j                  d
   j!                  |
       | j                  d
   j!                  |       y| j                  j%                  |       y)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@   rJ   ekencrypted_keyz{}r|   
recipients)rC   rN   rG   rH   rL   r   rn   rs   wrapwrap_key_sizerJ   r
   rp   rh   rB   r   appendpoprF   )r-   keyr@   rj   r   r   recwrappedhnhns              r2   rM   zJWE.add_recipient   s    >>!011$..%0899fd# (F""6*11"5S"CM((3 1 1488R@5>7?#*4=C wCGGHd34A$$Q(9:B'OCMt||+MM#sB'4<<'LL&--c2,DLL0H)+DLL&A$,,.%)\\%5%5o%F/"4<<'"ll..x8(LL&--a0LL&--c2LL$r3   c           
         d| j                   vrt        d      |rdD ]  }|| j                   v st        d|z         d| j                   vrt        d      t        | j                   d         }dD ]  }||vst        d|z         d	| j                   v r9t        | j                   d	         d
k7  rt        d      | j                   d	   d   }n| j                   }d|v rt        |d         }t        | j                   d         }| j	                  ||      }t        |      | j                   d<   | j                         }| j                  |      \  }	}
| j                  |	|
|       |d= dj                  t        | j                   d         t        |j                  dd            t        | j                   d         t        | j                   d         t        | j                   d         g      S | j                   }t        |d         t        |d         t        | j                   d         d}
d|v rt        |d         |
d<   d|v rt        |d         |
d<   d|v rt        |d         |
d<   d	|v rZg |
d	<   |d	   D ]B  }i }d|v rt        |d         |d<   d|v rt        |d         |d<   |
d	   j                  |       D t        |
      S d|v rt        |d         |
d<   d|v rt        |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`
        r|   No available ciphertext)r=   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@   rv   r   ru   r{   r}   )r|   r{   r}   r?   r=   )rB   rT   r
   lenrh   r   rn   rs   r   joinr	   rp   r   )r-   compactinvalidrk   requiredr   r   nphrj   r   r   objes                r2   	serializezJWE.serialize	  sV    t||+%&?@@/ ,dll*-!#*+, ,,
 $,,.)JL L !k!:; , ;Hr)1/19:; ;;
 t||+t||L12a7-.LMMll<03ll3
  H. k!:;))!R0,7,<[)**,99"=Sc3+M88-dll;.GH-cggor.JK-dll4.@A-dll<.HI-dll5.AB	D E E ,,C!1#l2C!D)#d)4*4<<+>?AC c!#3C4D#EK #%0]1C%DM"|-c%j9E
s"$&L!|, 0CA&#-,S-AB /*3&1#h-&@(%,,Q/0 s## #c)(_)=> (s?$/H$>CMs##r3   c                     |D ]E  }|| j                   vrt        d|z        | j                   |   j                  r9t        d|z         y )NzUnknown critical header: "%s"z!Unsupported critical header: "%s")rE   r(   	supported)r-   r   rg   s      r2   _check_critzJWE._check_crita  s^     	5A,,,$%Dq%HII++A.88( *023*4 5 5	5r3   c
                     |j                  ||j                  ||      }
|j                  |
||||	      }| j                  j	                  d       |
| _        |S )NSuccess)unwrapr   decryptrK   r   rJ   )r-   r   r   r   enckeyr@   r=   r{   r|   r}   rJ   r   s               r2   _unwrap_decryptzJWE._unwrap_decryptj  sP    jjc//@{{3RS9y)r3   c                 X   | j                  |j                  dd             }| j                  |j                  di              |D ]8  }|| j                  v s| j                  j	                  ||       r/t        d       | j                  |j                  dd             }| j                  |j                  dd             }t        | j                  j                  dd            }d| j                  v r|d	t        | j                  d         z   z  }|j                  d
      }t        |t              r|}d| j                  v rI|j                  | j                  d         }	|	s't        dj!                  | j                  d               |	}|D ]o  }
	 | j#                  |||
|j                  dd      ||| j                  d   | j                  d   | j                  d   	      }| j$                  j'                  d        n d| j$                  vr[t        d      | j#                  ||||j                  dd      ||| j                  d   | j                  d   | j                  d   	      }|j                  dd       }|dk(  r+t/        j0                  t.        j2                         | _        y || _        y t7        d      # t(        $ r_}|
j                  d|
j+                               }| j$                  j'                  dj!                  |t-        |                   Y d }~d }~ww xY w)Nr@   r   zFailed header checkr   r   r>   ru   r=   rv   r<   r   zKey ID {} not in key setr   r3   r{   r|   r}   r   zKey [{}] failed: [{}]zNo working key found in key setr   rw   rz   )rn   rp   r   rE   check_headerr(   rY   r\   r	   rB   rI   rG   r   jose_headerget_keysr   formatr   rK   r   	Exception
thumbprintreprr~   
decompress	MAX_WBITSrC   rN   )r-   r   pperj   hdrr   r   r=   rd   kid_keysrg   r   r   keyidr   s                  r2   _decryptzJWE._decrypts  s   ""3778T#:; 	+, 	@Cd***++88dC()>??	@
 ud 34mmBFF5$/0t||//R@ADLL 3)$,,u*=>>>Cjj!c6"D(((<<(8(8(?@'(B(I(I(,(8(8(?)A B B <<//S!030M02Cd9K04\0J04U0C	ED
 OO**95< /#$EFF''S#(+(E(*Cd1C(,\(B(,U(;	=D 66%&u!__TDNN?CDN!DN233) ! <EE%8EOO**+B+I+I+0$q',; < <<s   A+K	L)
AL$$L)c                    d| j                   vrt        d      g | _        d}d| j                   v r(| j                   d   D ]  }	 | j                  ||        n	 | j                  || j                          | j                  s.|rt        d      t        d	t        | j                        z         y# t        $ rC}t        |t              rd}| j                  j                  dt        |      z         Y d}~d}~ww xY w# t        $ rC}t        |t              rd}| j                  j                  dt        |      z         Y d}~d}~ww xY w)
a@  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.

        :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.
        r|   r   Fr   TzFailed: [%s]NzKey Not found in JWKSetz%No recipient matched the provided key)rB   rT   rK   r   r   rG   r   r   r   rC   r(   )r-   r   
missingkeyr   r   s        r2   r   zJWE.decrypt  s=    t||+%&?@@
4<<'||L1 EEMM#s+EAc4<<0 ~~#$=>>  "')-doo)>"? @ @  ! E!!]3%)
OO**>DG+CDDE  Aa/!%J&&~Q'?@@As0   B1D  1	C=:9C88C= 	E	9EEc                 D   i | _         d| _        d| _        i }	 	 t        |      }t	        |d         |d<   t	        |d         |d<   t	        |d         |d<   d|v r"t	        |d         }|j                  d      |d<   d|v rt        |d         |d<   d|v rt	        |d         |d<   d	|v rPg |d	<   |d	   D ]B  }i }d
|v rt	        |d
         |d
<   d|v rt        |d         |d<   |d	   j                  |       D n*d
|v rt	        |d
         |d
<   d|v rt        |d         |d<   || _         |r| j                  |       yy# t        $ r}|j                  d      }t        |      dk7  rt               |t	        |d         }|j                  d      |d<   t	        |d         }	|	dk7  rt	        |d         |d
<   t	        |d         |d<   t	        |d         |d<   t	        |d         |d<   Y d}~d}~ww xY w# t        $ r}t        dt        |            |d}~ww xY w)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.
        Nr{   r|   r}   r>   r<   r?   r=   r   r   r@   rv      r   r   r3   rx         zInvalid format)rB   rC   rJ   r
   r   decoder   r   rN   splitr   r(   r   r   r   )
r-   raw_jwer   odjwepr   r   r   ekeys
             r2   deserializezJWE.deserialize  sq   ( .	C(5"7+*4:6$"243E"F,+DK8%$&(k):;A%&XXg%6AkN D('243F'GAm$D=/U<AeH4'&(AlO#L1 2*c1 0_1E F o.#s?*5c(m*DAhK,..q12 '$.,T/-BC /*4'&1$x.&A( DL
 LL %  5}}S)t9>(*1$T!W-!"'!2+'Q03;)9$q')BAo&*473$"247";,+DG4%5  	C !147;B	Cs=   DE &G; 	G8B#G3.G; 3G88G; ;	HHHc                 H    | j                   st        d      | j                   S )NzPlaintext not available)rC   rT   r^   s    r2   payloadzJWE.payload$  s    ~~%&?@@~~r3   c                     | j                  | j                  j                  d            }t        |      dk(  rt	        d      |S )Nr@   r   zJOSE Header not available)rn   rB   rp   r   rT   )r-   rj   s     r2   r   zJWE.jose_header*  s=    ""4<<#3#3H#=>r7a<%&ABB	r3   c                 6     |        }|j                  |       |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   s      r2   from_jose_tokenzJWE.from_jose_token1  s     e
r3   c                 4   t        |t              sy	 | j                         |j                         k(  S # t        $ rZ d| j                  i}|j                  | j                         d|j                  i}|j                  |j                         ||k(  cY S w xY w)NFrC   )rG   r:   r   r   rC   rF   rB   )r-   otherdata1data2s       r2   __eq__z
JWE.__eq__B  s    %%	">>#u'888 	" $..1ELL& %//2ELL'E>!	"s    4 A BBc                 b    	 | j                         S # t        $ r | j                         cY S w xY wN)r   r   __repr__r^   s    r2   __str__zJWE.__str__N  s/    	#>>## 	#==?"	#s    ..c                 j   	 d| j                          dS # t        $ r t        | j                        }| j                  j                  d      }| j                  j                  d      }| j                  j                  d      }| j                  }d| dd| dz   d	| dz   d
| d| dz   cY S w xY w)NzJWE.from_json_token("z")r>   r?   r=   zJWE(plaintext=z, z
protected=zunprotected=zaad=z, algs=))r   r   r   rC   rB   rp   rA   )r-   rC   r>   r?   r=   rO   s         r2   r   zJWE.__repr__T  s    	.*4>>+;*<B?? 		.T^^,I((5I,,**=9K,,""5)C%%D#I;b1	{"-.!+b12 #gdV1-. .		.s    BB21B2)NNNNNNNNr   )F)r4   r5   r6   r7   r,   rY   r\   propertyr_   setterrh   rn   rs   r   rM   r   r   r   r   r   r   r   r   classmethodr   r   r   r    r3   r2   r:   r:   J   s    
 DH=A!%/Nb%( 
( 
( " "
	"&5%nV$p5:4x'@RJX  
     
"#.r3   r:   )r~   jwcryptor   jwcrypto.commonr   r   r   r   r   r	   r
   r   jwcrypto.jwar   jwcrypto.jwkr   rD   rS   r(   InvalidCEKeyLengthInvalidJWEKeyLengthInvalidJWEKeyTyperT   r:   r   r3   r2   <module>r      sF     6 C > 4   {E4>5udDI6tTJ}eUDA~ueTBxd;{E5$?8%MCU$d,#$J$)5$8vudD9~udDA
D$= " *
%  !2[ 2& .. 00 ,, 00 V. V.r3   