
    w,                         S r SSKJr  SSKJr  SSKJr  SSK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\
R0                  5      rg)z)Encrypt a plaintext file using a raw key.    )absolute_import)division)unicode_literalsN)
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
)
RawEncrypt$   a
  Encrypt a plaintext file using a raw key.

Encrypts the given plaintext file using the given CryptoKey containing a raw
key and writes the result to the named ciphertext file.
The plaintext file must not be larger than 64KiB.
For the AES-CBC algorithms, no server-side padding is being done,
so the plaintext must be a multiple of the block size.

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.

The initialization vector (flag `--initialization-vector-file`) is only
supported for `AES-CBC` and `AES-CTR` algorithms, and must be 16B in length.

Therefore, both additional authenticated data and initialization vector can't
be provided during encryption. If an additional authenticated data file is
provided, its contents must also be provided during decryption.
The file must not be larger than 64KiB.

The flag `--version` indicates the version of the key to use for
encryption.

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 encrypts the file `path/to/input/plaintext`.
The file will be encrypted using the `AES-GCM` CryptoKey `KEYNAME` from the
KeyRing `KEYRING` in the `global` location using the additional authenticated
data file `path/to/input/aad`.
The resulting ciphertext will be written to `path/to/output/ciphertext`.

  $ {command} \
      --key=KEYNAME \
      --keyring=KEYRING \
      --location=global \
      --plaintext-file=path/to/input/plaintext \
      --additional-authenticated-data-file=path/to/input/aad \
      --ciphertext-file=path/to/output/ciphertext

The following command reads and encrypts the file `path/to/input/plaintext`.
The file will be encrypted using the `AES-CBC` CryptoKey `KEYNAME` from the
KeyRing `KEYRING` in the `global` location using the initialization vector
stored at `path/to/input/aad`.
The resulting ciphertext will be written to `path/to/output/ciphertext`.

  $ {command} \
      --key=KEYNAME \
      --keyring=KEYRING \
      --location=global \
      --plaintext-file=path/to/input/plaintext \
      --initialization-vector-file=path/to/input/iv \
      --ciphertext-file=path/to/output/ciphertext
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 key to use for encryption.zto use for encryptionTz
to encryptz	to outputzfor encryption)r
   AddKeyResourceFlagsAddCryptoKeyVersionFlagAddPlaintextFileFlagAddCiphertextFileFlagAddIvFileFlagAddAadFileFlagAddSkipIntegrityVerification)parsers    lib/surface/kms/raw_encrypt.pyArgsRawEncrypt.Argsf   ss    	f&FG	!!&*A4H	v|4	4	 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RawEncrypt._ReadFileOrStdinp   sK    ))$t<D
4y9''
H
O
O 
 Kr   c                 $    UR                   (       + $ )N)skip_integrity_verification)r%   argss     r   _PerformIntegrityVerification(RawEncrypt._PerformIntegrityVerificationz   s    ////r   c           	         UR                   (       a(  UR                  (       a  [        R                  " SS5      eUR                  S:X  a7  UR                   S:X  d  UR                  S:X  a  [        R                  " SS5      e U R                  UR                  SS9nS	nUR                  (       a   U R                  UR                  SS9nS	nUR                   (       a\   U R                  UR                   [        S9n[        U5      [        :w  a*  [        R                  " SSR                  [        5      5      e[        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)NzE--initialization-vector-file and --additional-authenticated-data-filez2both parameters cannot be provided simultaneously.-z--plaintext-filez.multiple parameters cannot be read from stdin.i   )r'   z(Failed to read plaintext file [{0}]: {1}r   z<Failed to read additional authenticated data file [{0}]: {1}z4Failed to read initialization vector file [{0}]: {1}z--initialization-vector-filezthe IV size must be {0} bytes.)name)	plaintextinitializationVectoradditionalAuthenticatedDataplaintextCrc32cinitializationVectorCrc32c!additionalAuthenticatedDataCrc32c)r3   r4   r5   )initialization_vector_file"additional_authenticated_data_filer   InvalidArgumentExceptionplaintext_filer)   r   Errorr#   r$   CBC_CTR_IV_SIZEr"   r
   ParseCryptoKeyVersionNamecloudkms_baseGetMessagesModuleMCloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsRawEncryptRequestRelativeNamer.   r   Crc32cRawEncryptRequestrawEncryptRequest)r%   r-   r3   eaadivcrypto_key_refmessagesreqplaintext_crc32c	iv_crc32c
aad_crc32cs               r   _CreateRawEncryptRequest#RawEncrypt._CreateRawEncryptRequest}   s   ''33//2
>  c!''3.22c9//
N ''(;(;u'Mi C..	
##33u $ 
 
B&&

""++ # 
 
RO	#))*,33OD
 	

 44T:N..0H

`
`((* a C
 ))$//y1--#i==%j&88!&)*%.,6 9 c J '88!&) 9 c JE ;; ''
4
;
;!!1  [[ 
))JVD;;Q?
 	

 [[ 
))BII//
 	

sH   H 0I J$ I 0IIJ!,0JJ!$K-80K((K-c                    UR                   UR                   :w  a?  [        R                  " [        R                  " UR                   UR                   5      5      e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)aC  Verifies integrity fields in RawEncryptResponse.

Note: This methods assumes that self._PerformIntegrityVerification() is True
and that all request CRC32C fields were pupolated.
Args:
  req:
    messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsRawEncryptRequest()
    object
  resp: messages.RawEncryptResponse() object.

Returns:
  Void.
Raises:
  e2e_integrity.ServerSideIntegrityVerificationError if the server reports
  request integrity verification error.
  e2e_integrity.ClientSideIntegrityVerificationError if response integrity
  verification fails.
N)r2   r	   ResourceNameVerificationError#GetResourceNameMismatchErrorMessageverifiedPlaintextCrc32c$ClientSideIntegrityVerificationError'GetRequestToServerCorruptedErrorMessage)verifiedAdditionalAuthenticatedDataCrc32c"verifiedInitializationVectorCrc32cr   Crc32cMatches
ciphertextciphertextCrc32c*GetResponseFromServerCorruptedErrorMessage)r%   rL   resps      r   _VerifyResponseIntegrityFields)RawEncrypt._VerifyResponseIntegrityFields   s   * xx49977

;
;CHHdii
P 
 ''>>

?
?
A 
 99>>

?
?
A 
 22>>

?
?
A 
 1F1FGG>>

B
B
D  Hr   c                    [         R                  " 5       nU R                  U5      nS n UR                  R	                  U5      nU R                  U5      (       a  U R                  X45         [        R                  " UR                  UR                  SSS9  UR                  (       dW  UR                   (       aE  S[#        [$        R&                  " 5       5      S S -   n[(        R*                  " UUR                   SS9  g g g ! [
        R                   a   n[        R                  " U5         S nANS nAff = f! [(        R,                   a  n[.        R0                  " U5      eS nAff = f)NT)r    	overwritez./inialization_vector_   )rb   )r@   GetClientInstancerP   8projects_locations_keyRings_cryptoKeys_cryptoKeyVersionsr   apitools_exceptionsHttpBadRequestErrorr	   ProcessHttpBadRequestErrorr.   r_   r   WriteToFileOrStdoutciphertext_filer[   r9   r4   struuiduuid4r   WriteBinaryFileContentsr=   r   r#   )r%   r-   clientrL   r^   erroriv_file_namerG   s           r   RunRawEncrypt.Run	  s.   ,,.F

'
'
-CD6LLWW
d ))$//
))#4+	



 ,,1J1J/#djjl2CBQ2GG%%%%	
 2K, 22 6..u556& ;; +''**+s0   D -BD8 D5D00D58E'E""E' N)__name__
__module____qualname____firstlineno____doc__staticmethodr   r)   r.   rP   r_   rr   __static_attributes__rt   r   r   r   r   $   s8    ?B / /0Xt0d+r   r   )ry   
__future__r   r   r   rl   apitools.base.pyr   rf   googlecloudsdk.api_lib.cloudkmsr   r@   googlecloudsdk.calliopegooglecloudsdk.command_lib.kmsr   r	   r
   googlecloudsdk.corer   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r>   Commandr   rt   r   r   <module>r      sK    0 &  '  > A ( . 1 8 0 # 2 *C+ C+r   