
    &                         S r SSKJr  SSKJr  SSKJr  SSKJr  SSKJ	r
  SSKJ	r	  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  Sr " S S\	R.                  5      rg)z*Decrypt a ciphertext file using a raw key.    )absolute_import)division)unicode_literals)
exceptions)base)crc32c)e2e_integrity)flags)log)
console_io)files   c                   F    \ rS rSrSr\S 5       rS rS rS r	S r
S rS	rg
)
RawDecrypt#   aN  Decrypt a ciphertext file using a raw key.

`{command}` decrypts the given ciphertext file using the given CryptoKey
containing a raw key and writes the result to the named plaintext file.
The ciphertext file must not be larger than 64KiB.

The supported algorithms are: `AES-128-GCM`, `AES-256-GCM`, `AES-128-CBC`,
`AES-256-CBC`, `AES-128-CTR`, `and AES-256-CTR`.

`AES-GCM` provides authentication which means that it accepts additional
authenticated data (AAD). So, the flag `--additional-authenticated-data-file`
is only valid with `AES-128-GCM` and `AES-256-GCM` algorithms. If AAD is
provided during encryption, it must be provided during decryption too.
The file must not be larger than 64KiB.

If `--plaintext-file` or `--additional-authenticated-data-file` or
`--initialization-vector-file` is set to '-', that file is read from stdin.
Similarly, if `--ciphertext-file` is set to '-', the ciphertext is written
to stdout.

By default, the command performs integrity verification on data sent to and
received from Cloud KMS. Use `--skip-integrity-verification` to disable
integrity verification.

## EXAMPLES
The following command reads and decrypts the file `path/to/input/ciphertext`.
The file will be decrypted using the CryptoKey `KEYNAME` containing a raw key,
from the KeyRing `KEYRING` in the `global` location. It uses the additional
authenticated data file `path/to/input/aad` (only valid with the `AES-GCM`
algorithms) and the initialization vector file `path/to/input/iv`.
The resulting plaintext will be written to `path/to/output/plaintext`.

  $ {command} \
      --key=KEYNAME \
      --keyring=KEYRING \
      --location=global \
      --ciphertext-file=path/to/input/ciphertext \
      --additional-authenticated-data-file=path/to/input/aad \
      --initialization-vector-file=path/to/input/iv \
      --plaintext-file=path/to/output/plaintext
c                 D   [         R                  " U S5        [         R                  " U SS5        [         R                  " U S5        [         R                  " U S5        [         R
                  " U S5        [         R                  " U 5        [         R                  " U 5        g )Nz$The (raw) key to use for decryption.zto use for decryptionTzto store the decrypted dataz
to decryptzfor decryption)r
   AddKeyResourceFlagsAddCryptoKeyVersionFlagAddPlaintextFileFlagAddCiphertextFileFlagAddIvFileFlagAddAadFileFlagAddSkipIntegrityVerification)parsers    lib/surface/kms/raw_decrypt.pyArgsRawDecrypt.ArgsN   st    	f&LM	!!&*A4H	v'DE	5	 01	 	&&v.    c                     [         R                  " USS9n[        U5      U:  a%  [        R                  " SR                  X5      5      eU$ )NT)binaryz<The file [{0}] is larger than the maximum size of {1} bytes.)r   ReadFromFileOrStdinlenr   BadFileExceptionformat)selfpath	max_bytesdatas       r   _ReadFileOrStdinRawDecrypt._ReadFileOrStdinX   sK    ))$t<D
4y9''
H
O
O 
 Kr   c                 $    UR                   (       + $ )N)skip_integrity_verification)r%   argss     r   _PerformIntegrityVerification(RawDecrypt._PerformIntegrityVerificationb   s    ////r   c           	         UR                   S:X  a'  UR                  S:X  a  [        R                  " SS5      eUR                   S:X  a'  UR                  S:X  a  [        R                  " SS5      eUR                  S:X  a'  UR                  S:X  a  [        R                  " SS5      e U R                  UR                   SS9n U R                  UR                  [        S9n[        U5      [        :w  a*  [        R                  " S
SR                  [        5      5      eSnUR                  (       a   U R                  UR                  SS9n[        R                  " U5      n[        R                  " 5       nUR!                  UR#                  5       S9nU R%                  U5      (       a]  [&        R(                  " U5      n	[&        R(                  " U5      n
[&        R(                  " U5      nUR+                  UUUU	U
US9Ul        U$ UR+                  UUUS9Ul        U$ ! [        R                   a5  n[        R                  " SR                  UR                   U5      5      eS nAff = f! [        R                   a5  n[        R                  " S	R                  UR                  U5      5      eS nAff = f! [        R                   a5  n[        R                  " SR                  UR                  U5      5      eS nAff = f)N-z2--ciphertext-file and --initialization-vector-filez)both parameters can't be read from stdin.z:--ciphertext-file and --additional-authenticated-data-filezE--initialization-vector-file and --additional-authenticated-data-filei   )r'   z)Failed to read ciphertext file [{0}]: {1}z4Failed to read initialization vector file [{0}]: {1}z--initialization-vector-filezthe IV size must be {0} bytes.r   i   z<Failed to read additional authenticated data file [{0}]: {1})name)
ciphertextinitializationVectoradditionalAuthenticatedDataciphertextCrc32cinitializationVectorCrc32c!additionalAuthenticatedDataCrc32c)r3   r4   r5   )ciphertext_fileinitialization_vector_filer   InvalidArgumentException"additional_authenticated_data_filer)   r   Errorr#   r$   CBC_CTR_IV_SIZEr"   r
   ParseCryptoKeyVersionNamecloudkms_baseGetMessagesModuleMCloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsRawDecryptRequestRelativeNamer.   r   Crc32cRawDecryptRequestrawDecryptRequest)r%   r-   r3   eivaadcrypto_key_refmessagesrequestciphertext_crc32c	iv_crc32c
aad_crc32cs               r   _CreateRawDecryptRequest#RawDecrypt._CreateRawDecryptRequeste   s   s"t'F'F#'M//
>
5  	#33s://
F
5  	''3.33s://2
5  ((


) ) j
  

)
)_ ! b 2w/!''
(
*
1
1/
B 
 C..	
##33u $ 
 44T:N..0Hdd((* e G
 ))$// --
3--#i==%j"*"<"<!&),%.,6 #= #g N #+"<"<!&) #= #g NA ;; ''
5
<
<""A  ;; ''
@
G
G--q ( [[ 
))JVD;;Q?
 	

sH   'H I* 1J6 I'20I""I'*J3>0J..J36K?
0K::K?c                    UR                   (       d)  [        R                  " [        R                  " 5       5      eUR                  (       d)  [        R                  " [        R                  " 5       5      eUR
                  (       d)  [        R                  " [        R                  " 5       5      e[        R                  " UR                  UR                  5      (       d)  [        R                  " [        R                  " 5       5      eg)z&Verifies integrity fields in response.N)verifiedCiphertextCrc32cr	   $ClientSideIntegrityVerificationError'GetRequestToServerCorruptedErrorMessage)verifiedAdditionalAuthenticatedDataCrc32c"verifiedInitializationVectorCrc32cr   Crc32cMatches	plaintextplaintextCrc32c*GetResponseFromServerCorruptedErrorMessage)r%   resps     r   _VerifyResponseIntegrityFields)RawDecrypt._VerifyResponseIntegrityFields   s     ((>>

?
?
A 
 99>>

?
?
A 
 22>>

?
?
A 
 0D0DEE>>

B
B
D  Fr   c                    S nU R                  U5      n[        R                  " 5       n UR                  R	                  U5      nU R                  U5      (       a  U R                  U5         UR                  cA  [        R                  " UR                  5          S S S 5        [        R                   " S5        g [        R"                  " UR                  UR                  SSS9  g ! [
        R                   a   n[        R                  " U5         S nANS nAff = f! , (       d  f       N= f! [        R$                   a  n[&        R(                  " U5      eS nAff = f)NzDecrypted file is emptyT)r    	overwrite)rP   r@   GetClientInstance8projects_locations_keyRings_cryptoKeys_cryptoKeyVersionsr   apitools_exceptionsHttpBadRequestErrorr	   ProcessHttpBadRequestErrorr.   r]   rY   r   
FileWriterplaintext_filer   PrintWriteToFileOrStdoutr=   r   r#   )r%   r-   responserL   clienterrorrG   s          r   RunRawDecrypt.Run   s   H++D1G,,.F6PP[[
h ))$//
))(3+				#d112
 3 			+,!3!3DD	
 22 6..u556 32 ;; +''**+sM   C' --D/ DD/ ;+D/ 'D;DD
D,(D/ /EEE N)__name__
__module____qualname____firstlineno____doc__staticmethodr   r)   r.   rP   r]   rm   __static_attributes__ro   r   r   r   r   #   s7    (T / /0aF6+r   r   N)rt   
__future__r   r   r   apitools.base.pyr   rc   googlecloudsdk.api_lib.cloudkmsr   r@   googlecloudsdk.calliopegooglecloudsdk.command_lib.kmsr   r	   r
   googlecloudsdk.corer   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r>   Commandr   ro   r   r   <module>r      sH    1 &  ' > A ( . 1 8 0 # 2 *[+ [+r   