def _CreateMacVerifyRequest(self, args):
    try:
      # The MacVerify API limits the input data to 64KiB.
      data = self._ReadFileOrStdin(args.input_file, max_bytes=65536)
    except EnvironmentError as e:
      raise exceptions.BadFileException(
          'Failed to read input file [{0}]: {1}'.format(args.input_file, e))
    try:
      # We currently only support signatures up to SHA512 length (64 bytes).
      mac = self._ReadFileOrStdin(args.signature_file, max_bytes=64)
    except EnvironmentError as e:
      raise exceptions.BadFileException(
          'Failed to read input file [{0}]: {1}'.format(args.input_file, e))

    messages = cloudkms_base.GetMessagesModule()
    req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsMacVerifyRequest(  # pylint: disable=line-too-long
        name=flags.ParseCryptoKeyVersionName(args).RelativeName())

    if self._PerformIntegrityVerification(args):
      data_crc32c = crc32c.Crc32c(data)
      mac_crc32c = crc32c.Crc32c(mac)
      req.macVerifyRequest = messages.MacVerifyRequest(
          data=data, mac=mac, dataCrc32c=data_crc32c, macCrc32c=mac_crc32c)
    else:
      req.macVerifyRequest = messages.MacVerifyRequest(data=data, mac=mac)

    return req
예제 #2
0
    def _CreateEncryptRequest(self, args):
        if (args.plaintext_file == '-'
                and args.additional_authenticated_data_file == '-'):
            raise exceptions.InvalidArgumentException(
                '--plaintext-file',
                '--plaintext-file and --additional-authenticated-data-file cannot '
                'both read from stdin.')

        try:
            # The Encrypt API limits the plaintext to 64KiB.
            plaintext = self._ReadFileOrStdin(args.plaintext_file,
                                              max_bytes=65536)
        except files.Error as e:
            raise exceptions.BadFileException(
                'Failed to read plaintext file [{0}]: {1}'.format(
                    args.plaintext_file, e))

        aad = None
        if args.additional_authenticated_data_file:
            try:
                # The Encrypt API limits the AAD to 64KiB.
                aad = self._ReadFileOrStdin(
                    args.additional_authenticated_data_file, max_bytes=65536)

            except files.Error as e:
                raise exceptions.BadFileException(
                    'Failed to read additional authenticated data file [{0}]: {1}'
                    .format(args.additional_authenticated_data_file, e))

        if args.version:
            crypto_key_ref = flags.ParseCryptoKeyVersionName(args)
        else:
            crypto_key_ref = flags.ParseCryptoKeyName(args)

        messages = cloudkms_base.GetMessagesModule()

        req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysEncryptRequest(
            name=crypto_key_ref.RelativeName())

        # Populate request integrity fields.
        if self._PerformIntegrityVerification(args):
            plaintext_crc32c = crc32c.Crc32c(plaintext)
            # Set checksum if AAD is not provided for simpler response verification.
            aad_crc32c = crc32c.Crc32c(
                aad) if aad is not None else crc32c.Crc32c(b'')
            req.encryptRequest = messages.EncryptRequest(
                plaintext=plaintext,
                additionalAuthenticatedData=aad,
                plaintextCrc32c=plaintext_crc32c,
                additionalAuthenticatedDataCrc32c=aad_crc32c)
        else:
            req.encryptRequest = messages.EncryptRequest(
                plaintext=plaintext, additionalAuthenticatedData=aad)

        return req
예제 #3
0
  def _CreateAsymmetricSignRequest(self, args):
    try:
      digest = get_digest.GetDigest(args.digest_algorithm, args.input_file)
    except EnvironmentError as e:
      raise exceptions.BadFileException(
          'Failed to read input file [{0}]: {1}'.format(args.input_file, e))

    messages = cloudkms_base.GetMessagesModule()
    req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsAsymmetricSignRequest(  # pylint: disable=line-too-long
        name=flags.ParseCryptoKeyVersionName(args).RelativeName())

    if self._PerformIntegrityVerification(args):
      # args.digest_algorithm has been verified in get_digest.GetDigest()
      digest_crc32c = crc32c.Crc32c(getattr(digest, args.digest_algorithm))
      req.asymmetricSignRequest = messages.AsymmetricSignRequest(
          digest=digest, digestCrc32c=digest_crc32c)
    else:
      req.asymmetricSignRequest = messages.AsymmetricSignRequest(digest=digest)

    return req
    def _CreateAsymmetricSignRequestOnData(self, args):
        """Returns an AsymmetricSignRequest for use with a data input.

    Populates an AsymmetricSignRequest with its data field populated by data
    read from args.input_file. dataCrc32c is populated if integrity verification
    is not skipped.

    Args:
      args: Input arguments.

    Returns:
      An AsymmetricSignRequest with data populated and dataCrc32c populated if
      integrity verification is not skipped.

    Raises:
      exceptions.BadFileException: An error occurred reading the input file.
      This can occur if the file can't be read or if the file is larger than
      64 KiB.
    """
        try:
            # The Asymmetric Sign API limits the data input to 64KiB.
            data = self._ReadBinaryFile(args.input_file, max_bytes=65536)
        except files.Error as e:
            raise exceptions.BadFileException(
                'Failed to read input file [{0}]: {1}'.format(
                    args.input_file, e))

        messages = cloudkms_base.GetMessagesModule()
        req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsAsymmetricSignRequest(  # pylint: disable=line-too-long
            name=flags.ParseCryptoKeyVersionName(args).RelativeName())

        if self._PerformIntegrityVerification(args):
            data_crc32c = crc32c.Crc32c(data)
            req.asymmetricSignRequest = messages.AsymmetricSignRequest(
                data=data, dataCrc32c=data_crc32c)
        else:
            req.asymmetricSignRequest = messages.AsymmetricSignRequest(
                data=data)

        return req
예제 #5
0
    def _CreateAsymmetricDecryptRequest(self, args):
        try:
            ciphertext = console_io.ReadFromFileOrStdin(args.ciphertext_file,
                                                        binary=True)
        except files.Error as e:
            raise exceptions.BadFileException(
                'Failed to read ciphertext file [{0}]: {1}'.format(
                    args.ciphertext_file, e))

        messages = cloudkms_base.GetMessagesModule()
        crypto_key_ref = flags.ParseCryptoKeyVersionName(args)

        req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsAsymmetricDecryptRequest(  # pylint: disable=line-too-long
            name=crypto_key_ref.RelativeName())
        if self._PerformIntegrityVerification(args):
            ciphertext_crc32c = crc32c.Crc32c(ciphertext)
            req.asymmetricDecryptRequest = messages.AsymmetricDecryptRequest(
                ciphertext=ciphertext, ciphertextCrc32c=ciphertext_crc32c)
        else:
            req.asymmetricDecryptRequest = messages.AsymmetricDecryptRequest(
                ciphertext=ciphertext)

        return req
    def _CreateDecryptRequest(self, args):
        if (args.ciphertext_file == '-'
                and args.additional_authenticated_data_file == '-'):
            raise exceptions.InvalidArgumentException(
                '--ciphertext-file',
                '--ciphertext-file and --additional-authenticated-data-file cannot '
                'both read from stdin.')

        try:
            # The Encrypt API has a limit of 64K; the output ciphertext files will be
            # slightly larger. Check proactively (but generously) to avoid attempting
            # to buffer and send obviously oversized files to KMS.
            ciphertext = self._ReadFileOrStdin(args.ciphertext_file,
                                               max_bytes=2 * 65536)
        except files.Error as e:
            raise exceptions.BadFileException(
                'Failed to read ciphertext file [{0}]: {1}'.format(
                    args.ciphertext_file, e))

        aad = None
        if args.additional_authenticated_data_file:
            try:
                # The Encrypt API limits the AAD to 64KiB.
                aad = self._ReadFileOrStdin(
                    args.additional_authenticated_data_file, max_bytes=65536)
            except files.Error as e:
                raise exceptions.BadFileException(
                    'Failed to read additional authenticated data file [{0}]: {1}'
                    .format(args.additional_authenticated_data_file, e))

        crypto_key_ref = flags.ParseCryptoKeyName(args)

        # Check that the key id does not include /cryptoKeyVersion/ which may occur
        # as encrypt command does allow version, so it is easy for user to make a
        # mistake here.
        if '/cryptoKeyVersions/' in crypto_key_ref.cryptoKeysId:
            raise exceptions.InvalidArgumentException(
                '--key', '{} includes cryptoKeyVersion which is not valid for '
                'decrypt.'.format(crypto_key_ref.cryptoKeysId))

        messages = cloudkms_base.GetMessagesModule()

        req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysDecryptRequest(
            name=crypto_key_ref.RelativeName())

        # Populate request integrity fields.
        if self._PerformIntegrityVerification(args):
            ciphertext_crc32c = crc32c.Crc32c(ciphertext)
            # Set checksum if AAD is not provided for consistency.
            aad_crc32c = crc32c.Crc32c(
                aad) if aad is not None else crc32c.Crc32c(b'')
            req.decryptRequest = messages.DecryptRequest(
                ciphertext=ciphertext,
                additionalAuthenticatedData=aad,
                ciphertextCrc32c=ciphertext_crc32c,
                additionalAuthenticatedDataCrc32c=aad_crc32c)
        else:
            req.decryptRequest = messages.DecryptRequest(
                ciphertext=ciphertext, additionalAuthenticatedData=aad)

        return req