
    ,hC              	          d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZ ddlmZ ddlmZ ddlmZmZmZmZmZmZmZ  G d d	      Z G d
 de      Z	 d dlmZmZ d dlmZ  G d de      Z G d de      Z de!de!de!fdZ"de!de!de!fdZ#de!de!de!fdZ$de!de!de!fdZ%de!de!de!de!fdZ&de!de!de!de!fdZ' G d$ d%      Z) e!g d&      Z*de!de!fd'Z+ G d( d)      Z, G d* d+      Z- G d, d-e      Z. G d. d/      Z/y# e($ rY  G d de      Z G d de      Z de!de!de!fdZ"de!de!de!fdZ#de!de!de!fd Z$de!de!de!fd!Z%de!de!de!de!fd"Z&de!de!de!de!fd#Z'Y w xY w)0    N)IntEnum)AnyDictOptionalTupleUnioncast   )logger_warningDependencyError)ArrayObjectByteStringObjectDictionaryObject	PdfObjectStreamObjectTextStringObjectcreate_string_objectc                   ,    e Zd ZdedefdZdedefdZy)	CryptBasedatareturnc                     |S N selfr   s     T/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/PyPDF2/_encryption.pyencryptzCryptBase.encrypt0           c                     |S r   r   r   s     r   decryptzCryptBase.decrypt3   r    r!   N)__name__
__module____qualname__bytesr   r#   r   r!   r   r   r   /   s(    E e E e r!   r   c                       e Zd Zy)CryptIdentityN)r$   r%   r&   r   r!   r   r)   r)   7   s    r!   r)   )AESARC4)padc                   <    e Zd ZdeddfdZdedefdZdedefdZy)CryptRC4keyr   Nc                     || _         y r   r/   r   r/   s     r   __init__zCryptRC4.__init__@   	    DHr!   r   c                 ^    t        j                  | j                        j                  |      S r   )r+   
ARC4Cipherr/   r   r   s     r   r   zCryptRC4.encryptC        ??488,44T::r!   c                 ^    t        j                  | j                        j                  |      S r   )r+   r6   r/   r#   r   s     r   r#   zCryptRC4.decryptF   r7   r!   r$   r%   r&   r'   r3   r   r#   r   r!   r   r.   r.   ?   s;    	 	$ 		; 	;% 	;	; 	;% 	;r!   r.   c                   <    e Zd ZdeddfdZdedefdZdedefdZy)CryptAESr/   r   Nc                     || _         y r   r1   r2   s     r   r3   zCryptAES.__init__J   r4   r!   r   c           	      F   t        t        d t        d      D                    }dt        |      dz  z
  |t        t        fdt              D                    z  }t	        j
                  | j                  t        j                  |      }||j                  |      z   S )Nc              3   H   K   | ]  }t        j                  d d        yw)r      N)randomrandint.0_s     r   	<genexpr>z#CryptAES.encrypt.<locals>.<genexpr>N   s      KA3!7 K    "   c              3   "   K   | ]  }  y wr   r   )rC   rD   ps     r   rE   z#CryptAES.encrypt.<locals>.<genexpr>P   s     #8!A#8s   )	r'   	bytearrayrangelenr*   newr/   MODE_CBCr   )r   r   ivaesrI   s       @r   r   zCryptAES.encryptM   sz    y Kr KKLBSY^#AE)#8uQx#8899D''$((CLL"5CD)))r!   c                     |d d }|dd  }t        j                  | j                  t         j                  |      }t	        |      dz  rt        |d      }|j                  |      }t	        |      dk(  r|S |d |d     S )NrG   r   )r*   rM   r/   rN   rL   r,   r#   )r   r   rO   rP   ds        r   r#   zCryptAES.decryptT   sx    crB9D''$((CLL"5C4y2~4}D!A1v{AbE6{"r!   r9   r   r!   r   r;   r;   I   s;    	 	$ 		* 	*% 	*
	# 
	#% 
	#r!   r;   r/   r   r   c                 J    t        j                  |       j                  |      S r   )r+   r6   r   r/   r   s     r   RC4_encryptrV   `       s#++D11r!   c                 J    t        j                  |       j                  |      S r   )r+   r6   r#   rU   s     r   RC4_decryptrY   c   rW   r!   c                 h    t        j                  | t         j                        j                  |      S r   )r*   rM   MODE_ECBr   rU   s     r   AES_ECB_encryptr\   f   "    wwsCLL)11$77r!   c                 h    t        j                  | t         j                        j                  |      S r   )r*   rM   r[   r#   rU   s     r   AES_ECB_decryptr_   i   r]   r!   rO   c                 j    t        j                  | t         j                  |      j                  |      S r   )r*   rM   rN   r   r/   rO   r   s      r   AES_CBC_encryptrb   l   $    wwsCLL"-55d;;r!   c                 j    t        j                  | t         j                  |      j                  |      S r   )r*   rM   rN   r#   ra   s      r   AES_CBC_decryptre   o   rc   r!   c                   <    e Zd ZdeddfdZdedefdZdedefdZy)r.   r/   r   Nc                    t        t        d            | _        d}t        d      D ]b  }|| j                  |   z   ||t        |      z     z   dz  }| j                  |   | j                  |   c| j                  |<   | j                  |<   d y )N   r   )listrK   SrL   )r   r/   jis       r   r3   zCryptRC4.__init__u   s~    %*%DFA3Z <]SSX%66#='+vvay$&&)$q	466!9<r!   r   c                 X   t        | j                        }t        d t        t        |            D              }d\  }}t        t        |            D ]B  }|dz   dz  }|||   z   dz  }||   ||   c||<   ||<   |||   ||   z   dz     }||   |z  ||<   D t	        t        |            S )Nc              3       K   | ]  }d   ywr   Nr   rB   s     r   rE   z#CryptRC4.encrypt.<locals>.<genexpr>~   s     3Qq3   )r   r   r
   rh   )ri   rj   rK   rL   r'   rJ   )r   r   rj   outrl   rk   kxs           r   r   zCryptRC4.encrypt|   s    TVVA3%D	"233CDAq3t9% %UcM1X$qT1Q4
!adqtad{c)*a1A% 3((r!   c                 $    | j                  |      S r   )r   r   s     r   r#   zCryptRC4.decrypt   s    <<%%r!   r9   r   r!   r   r.   r.   t   s;    	< 	<$ 	<
	) 
	)% 
	)	& 	&% 	&r!   c                   <    e Zd ZdeddfdZdedefdZdedefdZy)r;   r/   r   Nc                      y r   r   r2   s     r   r3   zCryptAES.__init__   s    r!   r   c                     t        d      Nz*PyCryptodome is required for AES algorithmr   r   s     r   r   zCryptAES.encrypt       !"NOOr!   c                     t        d      rx   r   r   s     r   r#   zCryptAES.decrypt   ry   r!   r9   r   r!   r   r;   r;      sA    	 	$ 		P 	P% 	P	P 	P% 	Pr!   c                 6    t        |       j                  |      S r   )r.   r   rU   s     r   rV   rV          }$$T**r!   c                 6    t        |       j                  |      S r   )r.   r#   rU   s     r   rY   rY      r|   r!   c                     t        d      rx   r   rU   s     r   r\   r\          JKKr!   c                     t        d      rx   r   rU   s     r   r_   r_      r   r!   c                     t        d      rx   r   ra   s      r   rb   rb      r   r!   c                     t        d      rx   r   ra   s      r   re   re      r   r!   c                   D    e Zd ZdedededdfdZdedefdZdedefd	Zy)
CryptFilterstmCryptstrCryptefCryptr   Nc                 .    || _         || _        || _        y r   )r   r   r   )r   r   r   r   s       r   r3   zCryptFilter.__init__   s     ! r!   objc                     t         S r   )NotImplemented)r   r   s     r   encrypt_objectzCryptFilter.encrypt_object   s    r!   c                    t        |t        t        f      r2| j                  j	                  |j
                        }t        |      }|S t        |t              r,| j                  j	                  |j                        |_	        |S t        |t              r7t        |j                               D ]  \  }}| j                  |      ||<    |S t        |t              r0t        t!        |            D ]  }| j                  ||         ||<    |S r   )
isinstancer   r   r   r#   original_bytesr   r   r   _datar   ri   itemsdecrypt_objectr   rK   rL   )r   r   r   dictkeyvaluerl   s         r   r   zCryptFilter.decrypt_object   s    c,.>?@==((););<D&t,C 
 \*--cii8CI 
 -."&syy{"3 :#2259G:
 
 [)3s8_ 5,,SV4A5
r!   )r$   r%   r&   r   r3   r   r   r   r   r!   r   r   r      sM    !-6AJ	) 	 ) 	 r!   r   ) (      N   ^   r   u      A   d   r   r   V   r?      r
      .   r   r         h   >      /            r   S   i   z   c                     | t         z   d d S )N    )_PADDING)r   s    r   _paddingr      s    8OSb!!r!   c                      e Zd Zededededededededefd	       Zed
edededefd       Zededededefd       Z	ededededefd       Z
edededededededededefd       Zed
ededededededededefd       Zy)AlgV4passwordrevkey_sizeo_entryP	id1_entrymetadata_encryptedr   c                    t        |       }t        j                  |      }|j                  |       |j                  t	        j
                  d|             |j                  |       |dk\  r|du r|j                  d       |j                         }	|dz  }
|dk\  r6t        d      D ](  }t        j                  |	d|
       j                         }	* |	d|
 S )	u	  
        Algorithm 2: Computing an encryption key.

        a) Pad or truncate the password string to exactly 32 bytes. If the
           password string is more than 32 bytes long,
           use only its first 32 bytes; if it is less than 32 bytes long, pad it
           by appending the required number of
           additional bytes from the beginning of the following padding string:
                < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08
                2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A >
           That is, if the password string is n bytes long, append
           the first 32 - n bytes of the padding string to the end
           of the password string. If the password string is empty (zero-length),
           meaning there is no user password,
           substitute the entire padding string in its place.

        b) Initialize the MD5 hash function and pass the result of step (a)
           as input to this function.
        c) Pass the value of the encryption dictionary’s O entry to the
           MD5 hash function. ("Algorithm 3: Computing
           the encryption dictionary’s O (owner password) value" shows how the
           O value is computed.)
        d) Convert the integer value of the P entry to a 32-bit unsigned binary
           number and pass these bytes to the
           MD5 hash function, low-order byte first.
        e) Pass the first element of the file’s file identifier array (the value
           of the ID entry in the document’s trailer
           dictionary; see Table 15) to the MD5 hash function.
        f) (Security handlers of revision 4 or greater) If document metadata is
           not being encrypted, pass 4 bytes with
           the value 0xFFFFFFFF to the MD5 hash function.
        g) Finish the hash.
        h) (Security handlers of revision 3 or greater) Do the following
           50 times: Take the output from the previous
           MD5 hash and pass the first n bytes of the output as input into a new
           MD5 hash, where n is the number of
           bytes of the encryption key as defined by the value of the encryption
           dictionary’s Length entry.
        i) Set the encryption key to the first n bytes of the output from the
           final MD5 hash, where n shall always be 5
           for security handlers of revision 2 but, for security handlers of
           revision 3 or greater, shall depend on the
           value of the encryption dictionary’s Length entry.
        <I   F   r      2   N)r   hashlibmd5updatestructpackdigestrK   )r   r   r   r   r   r   r   au_hashu_hash_digestlengthrD   s               r   compute_keyzAlgV4.compute_key   s    l XQgfkk$*+i !8*e3MM-.Q!82Y M 'M'6,B C J J LMWf%%r!   owner_passwordc                     t        |       }t        j                  |      j                         }|dk\  r3t	        d      D ]%  }t        j                  |      j                         }' |d|dz   }|S )uJ  
        Algorithm 3: Computing the encryption dictionary’s O (owner password) value.

        a) Pad or truncate the owner password string as described in step (a)
           of "Algorithm 2: Computing an encryption key".
           If there is no owner password, use the user password instead.
        b) Initialize the MD5 hash function and pass the result of step (a) as
           input to this function.
        c) (Security handlers of revision 3 or greater) Do the following 50 times:
           Take the output from the previous
           MD5 hash and pass it as input into a new MD5 hash.
        d) Create an RC4 encryption key using the first n bytes of the output
           from the final MD5 hash, where n shall
           always be 5 for security handlers of revision 2 but, for security
           handlers of revision 3 or greater, shall
           depend on the value of the encryption dictionary’s Length entry.
        e) Pad or truncate the user password string as described in step (a) of
           "Algorithm 2: Computing an encryption key".
        f) Encrypt the result of step (e), using an RC4 encryption function with
           the encryption key obtained in step (d).
        g) (Security handlers of revision 3 or greater) Do the following 19 times:
           Take the output from the previous
           invocation of the RC4 function and pass it as input to a new
           invocation of the function; use an encryption
           key generated by taking each byte of the encryption key obtained in
           step (d) and performing an XOR
           (exclusive or) operation between that byte and the single-byte value
           of the iteration counter (from 1 to 19).
        h) Store the output from the final invocation of the RC4 function as
           the value of the O entry in the encryption dictionary.
        r   r   Nr   )r   r   r   r   rK   )r   r   r   r   o_hash_digestrD   rc4_keys          r   compute_O_value_keyzAlgV4.compute_O_value_key2  so    B ^$A--/!82Y D 'M : A A CD  (a-0r!   r   user_passwordc                     t        |      }t        | |      }|dk\  r:t        dd      D ]+  t        t	        fd| D                    }t        ||      }- |S )z See :func:`compute_O_value_key`.r   r
      c              3   (   K   | ]	  }|z    y wr   r   rC   rs   rl   s     r   rE   z(AlgV4.compute_O_value.<locals>.<genexpr>d       %=a!e%=   )r   rV   rK   r'   rJ   )r   r   r   r   rc4_encr/   rl   s         @r   compute_O_valuezAlgV4.compute_O_value]  s_     ]#gq)!81b\ 4I%=W%==>%c734 r!   r/   c                 F   |dk  rt        | t              }|S 	 t        j                  t              }|j	                  |       t        | |j                               }t        dd      D ]+  t        t        fd| D                    }t        ||      }- t        |      S )u]  
        Algorithm 4: Computing the encryption dictionary’s U (user password) value.

        (Security handlers of revision 2)

        a) Create an encryption key based on the user password string, as
           described in "Algorithm 2: Computing an encryption key".
        b) Encrypt the 32-byte padding string shown in step (a) of
           "Algorithm 2: Computing an encryption key", using an RC4 encryption
           function with the encryption key from the preceding step.
        c) Store the result of step (b) as the value of the U entry in the
           encryption dictionary.
           r
   r   c              3   (   K   | ]	  }|z    y wr   r   r   s     r   rE   z(AlgV4.compute_U_value.<locals>.<genexpr>  s     %9a!e%9r   )
rV   r   r   r   r   r   rK   r'   rJ   r   )r/   r   r   r   r   r   r   rl   s          @r   compute_U_valuezAlgV4.compute_U_valueh  s     !8X.EL	2 X&i c6==?3q" 	4AI%9S%99:G!'73G	4   r!   u_entryc           	          t         j                  | ||||||      }t         j                  |||      }	|dk\  r
|	dd }	|dd }|	|k7  rd}|S )u  
        Algorithm 6: Authenticating the user password.

        a) Perform all but the last step of "Algorithm 4: Computing the encryption dictionary’s U (user password)
           value (Security handlers of revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U (user
           password) value (Security handlers of revision 3 or greater)" using the supplied password string.
        b) If the result of step (a) is equal to the value of the encryption dictionary’s U entry (comparing on the first 16
           bytes in the case of security handlers of revision 3 or greater), the password supplied is the correct user
           password. The key obtained in step (a) (that is, in the first step of "Algorithm 4: Computing the encryption
           dictionary’s U (user password) value (Security handlers of revision 2)" or "Algorithm 5: Computing the
           encryption dictionary’s U (user password) value (Security handlers of revision 3 or greater)") shall be used
           to decrypt the document.
        r   NrG   r!   )r   r   r   )
r   r   r   r   r   r   r   r   r/   u_values
             r   verify_user_passwordzAlgV4.verify_user_password  si    0 3'1iAS
 ''S)<!8crlGcrlGgC
r!   c           
         t         j                  | ||      }|dk  rt        ||      }	n=|}	t        ddd      D ]+  t	        t        fd|D                    }
t        |
|	      }	- t         j                  |	|||||||      S )u  
        Algorithm 7: Authenticating the owner password.

        a) Compute an encryption key from the supplied password string, as described in steps (a) to (d) of
           "Algorithm 3: Computing the encryption dictionary’s O (owner password) value".
        b) (Security handlers of revision 2 only) Decrypt the value of the encryption dictionary’s O entry, using an RC4
           encryption function with the encryption key computed in step (a).
           (Security handlers of revision 3 or greater) Do the following 20 times: Decrypt the value of the encryption
           dictionary’s O entry (first iteration) or the output from the previous iteration (all subsequent iterations),
           using an RC4 encryption function with a different encryption key at each iteration. The key shall be
           generated by taking the original key (obtained in step (a)) and performing an XOR (exclusive or) operation
           between each byte of the key and the single-byte value of the iteration counter (from 19 to 0).
        c) The result of step (b) purports to be the user password. Authenticate this user password using "Algorithm 6:
           Authenticating the user password". If it is correct, the password supplied is the correct owner password.
        r      rR   c              3   (   K   | ]	  }|z    y wr   r   r   s     r   rE   z.AlgV4.verify_owner_password.<locals>.<genexpr>  r   r   )r   r   rY   rK   r'   rJ   r   )r   r   r   r   r   r   r   r   r   r   r/   rl   s              @r   verify_owner_passwordzAlgV4.verify_owner_password  s    4 ++NCJ!8'9M#M2r2& @I%=W%==> +C ?@ ))	
 		
r!   N)r$   r%   r&   staticmethodr'   intboolr   r   r   r   r   r   r   r!   r   r   r      s   A&A&A& A& 	A&
 A& A& !A& 
A& A&F (E ( (s (u ( (T  u 3 5   1!U 1! 1! 1!5 1! 1!f       	 
       !  
   D +
+
+
 +
 	+

 +
 +
 +
 !+
 
+
 +
r!   r   c                   R   e Zd Zededededededefd       Zedededededef
d	       Zededed
ededef
d       Zedededede	de	f
d       Z
ededededede	deeef   fd       Zedededeeef   fd       Zededededeeef   fd       Zededede	defd       Zy)AlgV5Rr   o_valueoe_valuer   r   c                     |dd }t         j                  | ||dd |dd       |dd k7  ryt        d t        d      D              }t         j                  | ||dd |dd       }t	        |||      }|S )	u	  
        Algorithm 3.2a Computing an encryption key.

        To understand the algorithm below, it is necessary to treat the O and U strings in the Encrypt dictionary
        as made up of three sections. The first 32 bytes are a hash value (explained below). The next 8 bytes are
        called the Validation Salt. The final 8 bytes are called the Key Salt.

        1. The password string is generated from Unicode input by processing the input string with the SASLprep
           (IETF RFC 4013) profile of stringprep (IETF RFC 3454), and then converting to a UTF-8 representation.
        2. Truncate the UTF-8 representation to 127 bytes if it is longer than 127 bytes.
        3. Test the password against the owner key by computing the SHA-256 hash of the UTF-8 password
           concatenated with the 8 bytes of owner Validation Salt, concatenated with the 48-byte U string. If the
           32-byte result matches the first 32 bytes of the O string, this is the owner password.
           Compute an intermediate owner key by computing the SHA-256 hash of the UTF-8 password
           concatenated with the 8 bytes of owner Key Salt, concatenated with the 48-byte U string. The 32-byte
           result is the key used to decrypt the 32-byte OE string using AES-256 in CBC mode with no padding and
           an initialization vector of zero. The 32-byte result is the file encryption key.
        4. Test the password against the user key by computing the SHA-256 hash of the UTF-8 password
           concatenated with the 8 bytes of user Validation Salt. If the 32 byte result matches the first 32 bytes of
           the U string, this is the user password.
           Compute an intermediate user key by computing the SHA-256 hash of the UTF-8 password
           concatenated with the 8 bytes of user Key Salt. The 32-byte result is the key used to decrypt the 32-byte
           UE string using AES-256 in CBC mode with no padding and an initialization vector of zero. The 32-byte
           result is the file encryption key.
        5. Decrypt the 16-byte Perms string using AES-256 in ECB mode with an initialization vector of zero and
           the file encryption key as the key. Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’. Bytes
           0-3 of the decrypted Perms entry, treated as a little-endian integer, are the user permissions. They
           should match the value in the P key.
        N   r   r   0   r!   c              3       K   | ]  }d   ywro   r   rB   s     r   rE   z.AlgV5.verify_owner_password.<locals>.<genexpr>       (1(rp   rG   r   calculate_hashr'   rK   re   )r   r   r   r   r   rO   tmp_keyr/   s           r   r   zAlgV5.verify_owner_password  s    B DS>  HgbngcrlKs| (eBi((&&q(GBrNGCRLQgr84
r!   ue_valuec                     |dd }t         j                  | ||dd d      |dd k7  ryt        d t        d      D              }t         j                  | ||dd d      }t	        |||      S )	z"See :func:`verify_owner_password`.Nr   r   r   r!   c              3       K   | ]  }d   ywro   r   rB   s     r   rE   z-AlgV5.verify_user_password.<locals>.<genexpr>#  r   rp   rG   r   r   )r   r   r   r   rO   r   s         r   r   zAlgV5.verify_user_password  sv    
 DS>8WR^SAWSb\Q(eBi((&&q(GBrNCHwH55r!   saltudatac                    t        j                  ||z   |z         j                         }| dk  r|S d}	 |dz  }||z   |z   }t        |d d |dd |dz        }t         j                  t         j                  t         j
                  ft        |d d       dz     } ||      j                         }|dk\  r|d   |dz
  k  rn|d d S )	N   r   r
   rG   r   @   r   rR   )r   sha256r   rb   sha384sha512sum)	r   r   r   r   KcountK1Ehash_fns	            r   r   zAlgV5.calculate_hash'  s     NN8d?U23::<q5HQJEA%B#2"R"r':A !CR&kAo	G
 
!!#A{qu
2  "vr!   r/   permsrI   r   c                 t    |rdnd}t        j                  d|      dz   |z   dz   }t        | |      }||dd k(  S )zBSee :func:`verify_owner_password` and :func:`compute_Perms_value`.   T   Fr   r      adbNr   )r   r   r_   )r/   r  rI   r   b8p1p2s          r   verify_permszAlgV5.verify_perms<  sI    
 (TT[[q!$77"<vES%(RW}r!   r   r   c                     t         j                  | |      \  }}t         j                  |||      \  }}t         j                  |||      }	|||||	dS )N)/U/UE/O/OE/Perms)r   r   r   compute_Perms_value)
r   r   r/   rI   r   r   r   r   r   r  s
             r   generate_valueszAlgV5.generate_valuesF  sb     "11-E!11.#wO))#q2DE
 	
r!   c                 H   t        d t        d      D              }|dd }|dd }t        j                  | |z         j	                         |z   |z   }t        j                  | |z         j	                         }t        d t        d      D              }t        |||      }||fS )up  
        Algorithm 3.8 Computing the encryption dictionary’s U (user password) and UE (user encryption key) values

        1. Generate 16 random bytes of data using a strong random number generator. The first 8 bytes are the
           User Validation Salt. The second 8 bytes are the User Key Salt. Compute the 32-byte SHA-256 hash of
           the password concatenated with the User Validation Salt. The 48-byte string consisting of the 32-byte
           hash followed by the User Validation Salt followed by the User Key Salt is stored as the U key.
        2. Compute the 32-byte SHA-256 hash of the password concatenated with the User Key Salt. Using this
           hash as the key, encrypt the file encryption key using AES-256 in CBC mode with no padding and an
           initialization vector of zero. The resulting 32-byte string is stored as the UE key.
        c              3   H   K   | ]  }t        j                  d d        ywr   rh   Nr@   	randrangerB   s     r   rE   z(AlgV5.compute_U_value.<locals>.<genexpr>f       I!V--a5IrF   rG   Nr   c              3       K   | ]  }d   ywro   r   rB   s     r   rE   z(AlgV5.compute_U_value.<locals>.<genexpr>l  r   rp   r'   rK   r   r   r   rb   )	r   r/   random_bytesval_saltkey_saltr   r   rO   r   s	            r   r   zAlgV5.compute_U_valueY  s     IuRyII##..H!45<<>IHT..H!45<<>(eBi(("7B4  r!   c                 T   t        d t        d      D              }|dd }|dd }t        j                  | |z   |z         j	                         |z   |z   }t        j                  | |z   |z         j	                         }t        d t        d      D              }t        |||      }	||	fS )u+  
        Algorithm 3.9 Computing the encryption dictionary’s O (owner password) and OE (owner encryption key) values.

        1. Generate 16 random bytes of data using a strong random number generator. The first 8 bytes are the
           Owner Validation Salt. The second 8 bytes are the Owner Key Salt. Compute the 32-byte SHA-256 hash
           of the password concatenated with the Owner Validation Salt and then concatenated with the 48-byte
           U string as generated in Algorithm 3.8. The 48-byte string consisting of the 32-byte hash followed by
           the Owner Validation Salt followed by the Owner Key Salt is stored as the O key.
        2. Compute the 32-byte SHA-256 hash of the password concatenated with the Owner Key Salt and then
           concatenated with the 48-byte U string as generated in Algorithm 3.8. Using this hash as the key,
           encrypt the file encryption key using AES-256 in CBC mode with no padding and an initialization vector
           of zero. The resulting 32-byte string is stored as the OE key.
        c              3   H   K   | ]  }t        j                  d d        ywr  r  rB   s     r   rE   z(AlgV5.compute_O_value.<locals>.<genexpr>  r  rF   rG   Nr   c              3       K   | ]  }d   ywro   r   rB   s     r   rE   z(AlgV5.compute_O_value.<locals>.<genexpr>  r   rp   r  )
r   r/   r   r  r   r!  r   r   rO   r   s
             r   r   zAlgV5.compute_O_valuep  s    " IuRyII##NN8h.89@@BXMPXX 	 ..H!4w!>?FFH(eBi(("7B4  r!   c                     |rdnd}t        d t        d      D              }t        j                  d|      dz   |z   dz   |z   }t	        | |      }|S )u  
        Algorithm 3.10 Computing the encryption dictionary’s Perms (permissions) value

        1. Extend the permissions (contents of the P integer) to 64 bits by setting the upper 32 bits to all 1’s. (This
           allows for future extension without changing the format.)
        2. Record the 8 bytes of permission in the bytes 0-7 of the block, low order byte first.
        3. Set byte 8 to the ASCII value ' T ' or ' F ' according to the EncryptMetadata Boolean.
        4. Set bytes 9-11 to the ASCII characters ' a ', ' d ', ' b '.
        5. Set bytes 12-15 to 4 bytes of random data, which will be ignored.
        6. Encrypt the 16-byte block using AES-256 in ECB mode with an initialization vector of zero, using the file
           encryption key as the key. The result (16 bytes) is stored as the Perms string, and checked for validity
           when the file is opened.
        r  r	  c              3   H   K   | ]  }t        j                  d d        ywr  r  rB   s     r   rE   z,AlgV5.compute_Perms_value.<locals>.<genexpr>  s     >6##As+>rF   r   r   r   r
  )r'   rK   r   r   r\   )r/   rI   r   r  rrr   r  s          r   r  zAlgV5.compute_Perms_value  sW     (TT>U1X>>{{4#&99B>G"LT*r!   N)r$   r%   r&   r   r   r'   r   r   r   r   r  r   r   r  r   r   r   r  r   r!   r   r   r     s   )))*/);@)KP)	) )V 	6	6	6*/	6;@	6		6 	6 #  e E e  (  %(>B	  


 
 	

 !
 
c3h
 
$ !% !e !eUl8K ! !, !!#!.3!	ue|	! !8  3 D U  r!   r   c                       e Zd ZdZdZdZy)PasswordTyper   r
   r   N)r$   r%   r&   NOT_DECRYPTEDUSER_PASSWORDOWNER_PASSWORDr   r!   r   r)  r)    s    MMNr!   r)  c                       e Zd Zdedededededededd	fd
ZdefdZ	de
dedede
fdZedededededef
d       Zdeeef   defdZdedeeef   fdZdedeeef   fdZedededd fd       Zy	)
EncryptionalgValgRentryfirst_id_entryStmFStrFEFFr   Nc                     || _         || _        || _        |j                  dd      | _        || _        || _        || _        || _        t        j                  | _        d | _        y )Nz/Lengthr   )r/  r0  r1  getr   r   r3  r4  r5  r)  r*  _password_type_key)r   r/  r0  r1  r2  r3  r4  r5  s           r   r3   zEncryption.__init__  s^     		
		)R0'		 +88%)	r!   c                 <    | j                   t        j                  k7  S r   )r8  r)  r*  )r   s    r   is_decryptedzEncryption.is_decrypted  s    ""l&@&@@@r!   r   idnum
generationc                    t        j                  d|      dd }t        j                  d|      dd }| j                  sJ | j                  }| j                  dk(  rdn| j                  dz  }|d| |z   |z   }t        j                  |      }	|	j                         dt        |dz   d       }
|	j                  d	       |	j                         dt        |dz   d       }|}| j                  | j                  |
||      }| j                  | j                  |
||      }| j                  | j                  |
||      }t        |||      }|j                  |      S )
u{	  
        Algorithm 1: Encryption of data using the RC4 or AES algorithms.

        a) Obtain the object number and generation number from the object identifier of the string or stream to be
           encrypted (see 7.3.10, "Indirect Objects"). If the string is a direct object, use the identifier of the indirect
           object containing it.
        b) For all strings and streams without crypt filter specifier; treating the object number and generation number
           as binary integers, extend the original n-byte encryption key to n + 5 bytes by appending the low-order 3
           bytes of the object number and the low-order 2 bytes of the generation number in that order, low-order byte
           first. (n is 5 unless the value of V in the encryption dictionary is greater than 1, in which case n is the value
           of Length divided by 8.)
           If using the AES algorithm, extend the encryption key an additional 4 bytes by adding the value “sAlT”,
           which corresponds to the hexadecimal values 0x73, 0x41, 0x6C, 0x54. (This addition is done for backward
           compatibility and is not intended to provide additional security.)
        c) Initialize the MD5 hash function and pass the result of step (b) as input to this function.
        d) Use the first (n + 5) bytes, up to a maximum of 16, of the output from the MD5 hash as the key for the RC4
           or AES symmetric key algorithms, along with the string or stream data to be encrypted.
           If using the AES algorithm, the Cipher Block Chaining (CBC) mode, which requires an initialization vector,
           is used. The block size parameter is set to 16 bytes, and the initialization vector is a 16-byte random
           number that is stored as the first 16 bytes of the encrypted stream or string.

        Algorithm 3.1a Encryption of data using the AES algorithm
        1. Use the 32-byte file encryption key for the AES-256 symmetric key algorithm, along with the string or
           stream data to be encrypted.
           Use the AES algorithm in Cipher Block Chaining (CBC) mode, which requires an initialization vector. The
           block size parameter is set to 16 bytes, and the initialization vector is a 16-byte random number that is
           stored as the first 16 bytes of the encrypted stream or string.
           The output is the encrypted data to be stored in the PDF file.
        z<iNr   r   r
      r   rG   s   sAlT)r   r   r9  r/  r   r   r   r   minr   
_get_cryptr3  r4  r5  r   r   )r   r   r<  r=  pack1pack2r/   nkey_datakey_hashr   
aes128_key
aes256_keyr   StrCryptr   cfs                    r   r   zEncryption.decrypt_object  s7   < D%(!,D*-bq1yyiiaAT]]a%7r7U?U*;;x(//#$4c!a%n5 __&'7QUB8
 
??499gz:N??499gz:N//$((GZL8W5  %%r!   methodr   rG  rH  c                 v    | dk(  rt        |      S | dk(  rt        |      S | dk(  r
t               S t        |      S )N/AESV3/AESV2	/Identity)r;   r)   r.   )rK  r   rG  rH  s       r   rA  zEncryption._get_crypt  sE     XJ''XJ''{" ?"G$$r!   r   c                 :   t        |t              r	 |j                  d      }n|}| j                  dk  r| j                  |      n| j                  |      \  }}|t        j                  k7  r|| _	        || _
        |S # t        $ r |j                  d      }Y sw xY w)Nzlatin-1zutf-8r   )r   strencode	Exceptionr/  	verify_v4	verify_v5r)  r*  r8  r9  )r   r   pwdr/   rcs        r   verifyzEncryption.verify  s    h$/ooi0 C)-a$..%T^^C=PR+++"$DDI	  /oog./s   A= =BBc           
         t        t        | j                  d         }t        t        | j                  d         }|dz   dz  }| j                  j                  d      }|r|j                  nd}t        t
        | j                  d   j                               j                  }t        t
        | j                  d   j                               j                  }t        j                  ||| j                  |||| j                  |      }|r|t        j                  fS t        j                  ||| j                  |||| j                  |      }|r|t        j                  fS dt        j                   fS )	N/R/P        /EncryptMetadataTr  r  r!   )r	   r   r1  r7  r   r   
get_objectr   r   r   r   r   r)  r,  r   r+  r*  )	r   r   r   r   emr   r   r   r/   s	            r   rT  zEncryption.verify_v4  sD   djj&'djj&'_+ZZ^^./)+RXX'D)9)D)D)FGVV'D)9)D)D)FGVV ))MMNN	
 3333((MMNN	
 2222L....r!   c                    t        t        | j                  d   j                               j                  }t        t        | j                  d   j                               j                  }t        t        | j                  d   j                               j                  }t        t        | j                  d   j                               j                  }t
        j                  | j                  ||||      }t        j                  }|s2t
        j                  | j                  |||      }t        j                  }|sdt        j                  fS t        t        | j                  d   j                               j                  }t        t        | j                  d         }	|	dz   dz  }	| j                  j                  d	d
      }
t
        j                  |||	|
      st!        dt"               ||fS )Nr  r  r  r  r!   r  r[  r\  r]  Tzignore '/Perms' verify failed)r	   r   r1  r^  r   r   r   r0  r)  r,  r   r+  r*  r   r7  r  r   r$   )r   r   r   r   oe_entryue_entryr/   rW  r  r   r   s              r   rU  zEncryption.verify_v5<  s   'D)9)D)D)FGVV'D)9)D)D)FGVV($**U*;*F*F*HIXX($**U*;*F*F*HIXX ))IIx(G
 ((,,TYY'8TC++B2222 %tzz(';'F'F'HIXXdjj&'_+!ZZ^^,>E!!#ua1CD:HEBwr!   encryption_entryc           	      <   | j                  d      }|dk7  rt        d      d| v rt        d      d}d}d}| j                  dd      }|d	vrt        d
| d      |dk\  r| d   }| j                  dd      }| j                  dd      }| j                  d|      }|dk7  r||   d   }|dk7  r||   d   }|dk7  r||   d   }d}||vrt        d      ||vrt        d| d      ||vrt        d| d      t        t        | d         }	t	        ||	| ||||      S )Nz/Filterz	/Standardz1only Standard PDF encryption handler is availablez
/SubFilterz/SubFilter NOT supported/V2z/Vr   )r
   r   r   r   r?  zEncryption V=z NOT supportedr   z/CFz/StmFrO  z/StrFz/EFFz/CFM)rO  re  rN  rM  z!StmF Method {StmF} NOT supported!zStrF Method z NOT supported!zEFF Method rZ  )r7  NotImplementedErrorr	   r   r.  )
rc  r2  filterr3  r4  r5  Vfiltersallowed_methodsr   s
             r   readzEncryption.readW  s   !%%i0[ %C  ++%&@AA  q)O#%aS&GHH6&u-G#''=D#''=D"&&vt4C{"t}V,{"t}V,k!cl6*FO?*)*MNN?*)Lo*NOO/))KuO*LMM&t,-!Q 0.$cRRr!   )r$   r%   r&   r   r   r'   rQ  r3   r   r;  r   r   r   r   rA  r   r)  rX  r   rT  rU  rk  r   r!   r   r.  r.    sG   ** *  	*
 * * * * 
*2Ad A3&) 3&C 3&S 3&Y 3&j 
%
%#
%16
%DI
%	
% 
%uUCZ0 \ #/% #/E%2E,F #/J% E%2E,F 6 'S/ 'S 'S< 'S 'Sr!   r.  )0r   r@   r   enumr   typingr   r   r   r   r   r	   _utilsr   errorsr   genericr   r   r   r   r   r   r   r   r)   Crypto.Cipherr*   r+   Crypto.Util.Paddingr,   r.   r;   r'   rV   rY   r\   r_   rb   re   ImportErrorr   r   r   r   r   r)  r.  r   r!   r   <module>rt     sb  8     : : " #   	I 	jL'';9 ;#9 #.2 2e 2 22 2e 2 28U 8% 8E 88U 8% 8E 8<U < <U <u <<U < <U <u <r 6 !#L"5 "U "~
 ~
Br rj7 VS VSo  3L&9 &.P9 P+ +e + ++ +e + +LU L% LE LLU L% LE LLU L LU Lu LLU L LU Lu Le3Ls   A$D AEE