Пример #1
0
def main(unused_argv):
    aead.register()
    daead.register()
    hybrid.register()
    mac.register()
    prf.register()
    signature.register()
    streaming_aead.register()
    jwt.register_jwt_mac()
    fake_kms.register_client()
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=2))
    testing_api_pb2_grpc.add_MetadataServicer_to_server(
        services.MetadataServicer(), server)
    testing_api_pb2_grpc.add_KeysetServicer_to_server(
        services.KeysetServicer(), server)
    testing_api_pb2_grpc.add_AeadServicer_to_server(services.AeadServicer(),
                                                    server)
    testing_api_pb2_grpc.add_DeterministicAeadServicer_to_server(
        services.DeterministicAeadServicer(), server)
    testing_api_pb2_grpc.add_MacServicer_to_server(services.MacServicer(),
                                                   server)
    testing_api_pb2_grpc.add_PrfSetServicer_to_server(
        services.PrfSetServicer(), server)
    testing_api_pb2_grpc.add_HybridServicer_to_server(
        services.HybridServicer(), server)
    testing_api_pb2_grpc.add_SignatureServicer_to_server(
        services.SignatureServicer(), server)
    testing_api_pb2_grpc.add_StreamingAeadServicer_to_server(
        services.StreamingAeadServicer(), server)
    testing_api_pb2_grpc.add_JwtServicer_to_server(jwt_service.JwtServicer(),
                                                   server)
    server.add_secure_port('[::]:%d' % FLAGS.port,
                           grpc.local_server_credentials())
    server.start()
    server.wait_for_termination()
Пример #2
0
def register():
    aead.register()
    daead.register()
    hybrid.register()
    cc_tink_config.register()
    _register_key_managers()
    _register_primitive_wrappers()
Пример #3
0
 def setUpClass(cls):
     super().setUpClass()
     aead.register()
     daead.register()
     mac.register()
     hybrid.register()
     signature.register()
Пример #4
0
def setUpModule():
    aead.register()
    daead.register()
    mac.register()
    hybrid.register()
    signature.register()
    testing_servers.start('key_generation_consistency')
Пример #5
0
def setUpModule():
    aead.register()
    daead.register()
    mac.register()
    hybrid.register()
    signature.register()
    testing_servers.start()
Пример #6
0
  def __init__(self, key_uri, creds, tmp_location=_TMP_LOCATION):
    """Init class for EncryptWithTink.

    Args:
      key_uri: string with the resource identifier for the KMS symmetric key
      creds: path to the creds.json file with the service account key for KMS
      tmp_location: temporary directory for encryption and decryption

    Returns:
      None
    """

    self.tmp_location = tmp_location
    # Make the tmp dir if it doesn't exist
    if not os.path.isdir(self.tmp_location):
      # noinspection PyUnusedLocal
      try:
        os.makedirs(self.tmp_location)
      except FileExistsError:
        # This is ok because the directory already exists
        pass
      except OSError as os_error:
        error_and_exit(str(os_error))

    # Initialize Tink
    try:
      aead.register()
      self.key_template = aead.aead_key_templates.AES128_EAX
      self.keyset_handle = tink.new_keyset_handle(self.key_template)
      gcp_client = gcpkms.GcpKmsClient(key_uri, creds)
      gcp_aead = gcp_client.get_aead(key_uri)
      self.env_aead = aead.KmsEnvelopeAead(self.key_template, gcp_aead)
    except TinkError as tink_init_error:
      error_and_exit('tink initialization failed: ' + str(tink_init_error))
Пример #7
0
def register():
    aead.register()
    daead.register()
    hybrid.register()
    mac.register()
    prf.register()
    signature.register()
    streaming_aead.register()
Пример #8
0
def main(unused_argv):
  aead.register()
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=2))
  testing_api_pb2_grpc.add_KeysetServicer_to_server(KeysetServicer(), server)
  testing_api_pb2_grpc.add_AeadServicer_to_server(AeadServicer(), server)
  server.add_secure_port('[::]:%d' % FLAGS.port,
                         grpc.local_server_credentials())
  server.start()
  server.wait_for_termination()
Пример #9
0
def main(argv):
    del argv  # Unused.

    # Initialise Tink
    try:
        aead.register()
    except tink.TinkError as e:
        logging.exception('Error initialising Tink: %s', e)
        return 1

    # Read the GCP credentials and setup client
    try:
        gcpkms.GcpKmsClient.register_client(FLAGS.kek_uri,
                                            FLAGS.gcp_credential_path)
    except tink.TinkError as e:
        logging.exception('Error initializing GCP client: %s', e)
        return 1

    # Create envelope AEAD primitive using AES256 GCM for encrypting the data
    try:
        template = aead.aead_key_templates.create_kms_envelope_aead_key_template(
            kek_uri=FLAGS.kek_uri,
            dek_template=aead.aead_key_templates.AES256_GCM)
        handle = tink.KeysetHandle.generate_new(template)
        env_aead = handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.exception('Error creating primitive: %s', e)
        return 1

    storage_client = storage.Client.from_service_account_json(
        FLAGS.gcp_credential_path)

    try:
        bucket_name, object_name = _get_bucket_and_object(FLAGS.gcs_blob_path)
    except ValueError as e:
        logging.exception('Error parsing GCS blob path: %s', e)
        return 1
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(object_name)
    associated_data = FLAGS.gcs_blob_path.encode('utf-8')

    if FLAGS.mode == 'encrypt':
        with open(FLAGS.local_path, 'rb') as input_file:
            output_data = env_aead.encrypt(input_file.read(), associated_data)
        blob.upload_from_string(output_data)

    elif FLAGS.mode == 'decrypt':
        ciphertext = blob.download_as_string()
        with open(FLAGS.local_path, 'wb') as output_file:
            output_file.write(env_aead.decrypt(ciphertext, associated_data))

    else:
        logging.error(
            'Error mode not supported. Please choose "encrypt" or "decrypt".')
        return 1
Пример #10
0
    def __init__(self, encoded_key):
      tink_config.register()
      aead.register()

      if (encoded_key==None):
        self.keyset_handle = tink.new_keyset_handle(aead.aead_key_templates.AES256_GCM)
      else:
        reader = tink.BinaryKeysetReader(base64.b64decode(encoded_key))
        self.keyset_handle = cleartext_keyset_handle.read(reader)
      self.key=self.keyset_handle.keyset_info()
      self.aead_primitive = self.keyset_handle.primitive(aead.Aead)
Пример #11
0
def main(argv):
    if len(argv) != 6 and len(argv) != 7:
        raise app.UsageError(
            'Expected 5 arguments, got %d.\n'
            'Usage: %s encrypt/decrypt kek-uri gcp-credential-file '
            'input-file output-file [associated-data]' %
            (len(argv) - 1, argv[0]))

    mode = argv[1]
    kek_uri = argv[2]
    gcp_credential_file = argv[3]
    input_file_path = argv[4]
    output_file_path = argv[5]
    associated_data = b'' if len(argv) == 6 else argv[6].encode('utf-8')

    # Initialise Tink
    try:
        aead.register()
    except tink.TinkError as e:
        logging.error('Error initialising Tink: %s', e)
        return 1

    # Read the GCP credentials and setup client
    try:
        gcpkms.GcpKmsClient.register_client(kek_uri, gcp_credential_file)
    except tink.TinkError as e:
        logging.error('Error initializing GCP client: %s', e)
        return 1

    # Create envelope AEAD primitive using AES256 GCM for encrypting the data
    try:
        template = aead.aead_key_templates.create_kms_envelope_aead_key_template(
            kek_uri=kek_uri, dek_template=aead.aead_key_templates.AES256_GCM)
        handle = tink.KeysetHandle.generate_new(template)
        env_aead = handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.error('Error creating primitive: %s', e)
        return 1

    with open(input_file_path, 'rb') as input_file:
        input_data = input_file.read()
        if mode == 'decrypt':
            output_data = env_aead.decrypt(input_data, associated_data)
        elif mode == 'encrypt':
            output_data = env_aead.encrypt(input_data, associated_data)
        else:
            logging.error(
                'Error mode not supported. Please choose "encrypt" or "decrypt".'
            )
            return 1

        with open(output_file_path, 'wb') as output_file:
            output_file.write(output_data)
Пример #12
0
def main(argv):
    if len(argv) != 5 and len(argv) != 6:
        raise app.UsageError(
            'Expected 4 or 5 arguments, got %d.\n'
            'Usage: %s encrypt/decrypt key-file input-file output-file '
            '[associated-data]' % (len(argv) - 1, argv[0]))

    mode = argv[1]
    key_file_path = argv[2]
    input_file_path = argv[3]
    output_file_path = argv[4]
    associated_data = b'' if len(argv) == 5 else bytes(argv[5], 'utf-8')

    # Initialise Tink
    try:
        aead.register()
    except tink.TinkError as e:
        logging.error('Error initialising Tink: %s', e)
        return 1

    # Read the keyset into a keyset_handle
    with open(key_file_path, 'rt') as keyset_file:
        try:
            text = keyset_file.read()
            keyset_handle = cleartext_keyset_handle.read(
                tink.JsonKeysetReader(text))
        except tink.TinkError as e:
            logging.exception('Error reading key: %s', e)
            return 1

    # Get the primitive
    try:
        cipher = keyset_handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.error('Error creating primitive: %s', e)
        return 1

    with open(input_file_path, 'rb') as input_file:
        input_data = input_file.read()
        if mode == 'decrypt':
            output_data = cipher.decrypt(input_data, associated_data)
        elif mode == 'encrypt':
            output_data = cipher.encrypt(input_data, associated_data)
        else:
            logging.error(
                'Error mode not supported. Please choose "encrypt" or "decrypt".'
            )
            return 1

        with open(output_file_path, 'wb') as output_file:
            output_file.write(output_data)
Пример #13
0
def main(argv):
    if len(argv) != 6:
        raise app.UsageError(
            'Expected 5 arguments, got %d.\n'
            'Usage: %s gcp-credentials key-uri input-file output-file [decrypt]'
            % (len(argv) - 1, argv[0]))

    mode = argv[1]
    gcp_credentials = argv[2]
    key_uri = argv[3]
    input_file_path = argv[4]
    output_file_path = argv[5]

    # Initialise Tink.
    try:
        aead.register()
    except tink.TinkError as e:
        logging.error('Error initialising Tink: %s', e)
        return 1

    # Read the GCP credentials and setup client
    try:
        gcp_client = gcpkms.GcpKmsClient(key_uri, gcp_credentials)
        gcp_aead = gcp_client.get_aead(key_uri)
    except tink.TinkError as e:
        logging.error('Error initializing GCP client: %s', e)
        return 1

    # Create envelope AEAD primitive using AES256 GCM for encrypting the data
    try:
        key_template = aead.aead_key_templates.AES256_GCM
        env_aead = aead.KmsEnvelopeAead(key_template, gcp_aead)
    except tink.TinkError as e:
        logging.error('Error creating primitive: %s', e)
        return 1

    with open(input_file_path, 'rb') as input_file:
        input_data = input_file.read()
        if mode == 'decrypt':
            output_data = env_aead.decrypt(input_data, b'envelope_example')
        elif mode == 'encrypt':
            output_data = env_aead.encrypt(input_data, b'envelope_example')
        else:
            logging.error(
                'Error mode not supported. Please choose "encrypt" or "decrypt".'
            )
            return 1

        with open(output_file_path, 'wb') as output_file:
            output_file.write(output_data)
Пример #14
0
def main(argv):
    del argv  # Unused.

    associated_data = b'' if not FLAGS.associated_data else bytes(
        FLAGS.associated_data, 'utf-8')

    # Initialise Tink
    try:
        aead.register()
    except tink.TinkError as e:
        logging.error('Error initialising Tink: %s', e)
        return 1

    # Read the GCP credentials and setup client
    try:
        gcpkms.GcpKmsClient.register_client(FLAGS.kek_uri,
                                            FLAGS.gcp_credential_path)
    except tink.TinkError as e:
        logging.error('Error initializing GCP client: %s', e)
        return 1

    # Create envelope AEAD primitive using AES256 GCM for encrypting the data
    try:
        template = aead.aead_key_templates.create_kms_envelope_aead_key_template(
            kek_uri=FLAGS.kek_uri,
            dek_template=aead.aead_key_templates.AES256_GCM)
        handle = tink.KeysetHandle.generate_new(template)
        env_aead = handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.error('Error creating primitive: %s', e)
        return 1

    with open(FLAGS.input_path, 'rb') as input_file:
        input_data = input_file.read()
        if FLAGS.mode == 'decrypt':
            output_data = env_aead.decrypt(input_data, associated_data)
        elif FLAGS.mode == 'encrypt':
            output_data = env_aead.encrypt(input_data, associated_data)
        else:
            logging.error(
                'Error mode not supported. Please choose "encrypt" or "decrypt".'
            )
            return 1

        with open(FLAGS.output_path, 'wb') as output_file:
            output_file.write(output_data)
Пример #15
0
def example():
  """Encrypt and decrypt using AEAD."""
  # Register the AEAD key managers. This is needed to create an Aead primitive
  # later.
  aead.register()

  # A keyset created with "tinkey create-keyset --key-template=AES256_GCM". Note
  # that this keyset has the secret key information in cleartext.
  keyset = r"""{
      "key": [{
          "keyData": {
              "keyMaterialType":
                  "SYMMETRIC",
              "typeUrl":
                  "type.googleapis.com/google.crypto.tink.AesGcmKey",
              "value":
                  "GiBWyUfGgYk3RTRhj/LIUzSudIWlyjCftCOypTr0jCNSLg=="
          },
          "keyId": 294406504,
          "outputPrefixType": "TINK",
          "status": "ENABLED"
      }],
      "primaryKeyId": 294406504
  }"""

  # Create a keyset handle from the cleartext keyset in the previous
  # step. The keyset handle provides abstract access to the underlying keyset to
  # limit the exposure of accessing the raw key material. WARNING: In practice
  # it is unlikely you will want to use a cleartext_keyset_handle, as it implies
  # that your key material is passed in cleartext which is a security risk.
  keyset_handle = cleartext_keyset_handle.read(tink.JsonKeysetReader(keyset))

  # Retrieve the Aead primitive we want to use from the keyset handle.
  primitive = keyset_handle.primitive(aead.Aead)

  # Use the primitive to encrypt a message. In this case the primary key of the
  # keyset will be used (which is also the only key in this example).
  ciphertext = primitive.encrypt(b'msg', b'associated_data')

  # Use the primitive to decrypt the message. Decrypt finds the correct key in
  # the keyset and decrypts the ciphertext. If no key is found or decryption
  # fails, it raises an error.
  output = primitive.decrypt(ciphertext, b'associated_data')
  # [END aead-basic-example]
  assert output == b'msg'
Пример #16
0
def main(argv):
    del argv  # Unused.

    associated_data = b'' if not FLAGS.associated_data else bytes(
        FLAGS.associated_data, 'utf-8')

    # Initialise Tink
    try:
        aead.register()
    except tink.TinkError as e:
        logging.error('Error initialising Tink: %s', e)
        return 1

    # Read the keyset into a keyset_handle
    with open(FLAGS.keyset_path, 'rt') as keyset_file:
        try:
            text = keyset_file.read()
            keyset_handle = cleartext_keyset_handle.read(
                tink.JsonKeysetReader(text))
        except tink.TinkError as e:
            logging.exception('Error reading key: %s', e)
            return 1

    # Get the primitive
    try:
        cipher = keyset_handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.error('Error creating primitive: %s', e)
        return 1

    with open(FLAGS.input_path, 'rb') as input_file:
        input_data = input_file.read()
        if FLAGS.mode == 'decrypt':
            output_data = cipher.decrypt(input_data, associated_data)
        elif FLAGS.mode == 'encrypt':
            output_data = cipher.encrypt(input_data, associated_data)
        else:
            logging.error(
                'Error mode not supported. Please choose "encrypt" or "decrypt".'
            )
            return 1

        with open(FLAGS.output_path, 'wb') as output_file:
            output_file.write(output_data)
Пример #17
0
def init_tink_env_aead(key_uri: str,
                       credentials: str) -> tink.aead.KmsEnvelopeAead:
    aead.register()

    try:
        gcp_client = gcpkms.GcpKmsClient(key_uri, credentials)
        gcp_aead = gcp_client.get_aead(key_uri)
    except tink.TinkError as e:
        logger.error("Error initializing GCP client: %s", e)
        raise e

    # Create envelope AEAD primitive using AES256 GCM for encrypting the data
    # This key should only be used for client-side encryption to ensure authenticity and integrity
    # of data.
    key_template = aead.aead_key_templates.AES256_GCM
    env_aead = aead.KmsEnvelopeAead(key_template, gcp_aead)

    print(f"Created envelope AEAD Primitive using KMS URI: {key_uri}")

    return env_aead
Пример #18
0
def main(argv):
  if len(argv) != 6:
    raise app.UsageError(
        'Expected 5 arguments, got %d.\n'
        'Usage: %s keyset-file operation input-file associated-data-file' %
        (len(argv) - 1, argv[0]))

  keyset_filename = argv[1]
  operation = argv[2]
  input_filename = argv[3]
  associated_data_filename = argv[4]
  output_filename = argv[5]

  logging.info(
      'Using keyset from file %s to AEAD-%s file %s with associated data '
      'from file %s.\nThe resulting output will be written to file %s',
      keyset_filename, operation, input_filename, associated_data_filename,
      output_filename)

  # Initialise Tink
  try:
    aead.register()
  except tink.TinkError as e:
    logging.error('Error initialising Tink: %s', e)
    return 1

  # Initialize KMS clients
  awskms.AwsKmsClient.register_client(AWS_KEY_URI, AWS_CREDENTIAL_PATH)
  gcpkms.GcpKmsClient.register_client(GCP_KEY_URI, GCP_CREDENTIAL_PATH)

  # Read the keyset into keyset_handle
  try:
    keyset_handle = read_keyset(keyset_filename)
  except tink.TinkError as e:
    logging.error('Error reading key: %s', e)
    return 1

  # Get the primitive
  try:
    cipher = keyset_handle.primitive(aead.Aead)
  except tink.TinkError as e:
    logging.error('Error creating primitive: %s', e)
    return 1

  # Read the input files
  with open(input_filename, 'rb') as input_file:
    input_data = input_file.read()
  with open(associated_data_filename, 'rb') as associated_data_file:
    aad = associated_data_file.read()

  # Compute the output
  if operation.lower() == 'encrypt':
    try:
      output_data = cipher.encrypt(input_data, aad)
    except tink.TinkError as e:
      logging.error('Error encrypting the input: %s', e)
      return 1
  elif operation.lower() == 'decrypt':
    try:
      output_data = cipher.decrypt(input_data, aad)
    except tink.TinkError as e:
      logging.error('Error decrypting the input: %s', e)
      return 1
  else:
    logging.error(
        'Did not recognise operation %s.\n'
        'Expected either "encrypt" or "decrypt"', operation)
    return 1

  with open(output_filename, 'wb') as output_file:
    output_file.write(output_data)

  logging.info('All done.')
def register():
    aead.register()
    daead.register()
    hybrid.register()
    mac.register()
    signature.register()
Пример #20
0
def setUpModule():
    aead.register()
    mac.register()
    daead.register()
    prf.register()
    testing_servers.start('key_version')
Пример #21
0
def main(argv):
  if len(argv) != 3 and len(argv) != 5:
    raise app.UsageError(
        'Invalid arguments.\n'
        'Usage: %s generate key-file.\n'
        'Usage: %s encrypt/decrypt key-file '
        'input-file output-file.' % (argv[0], argv[0])
        )

  mode = argv[1]
  if mode not in ('encrypt', 'decrypt', 'generate'):
    raise app.UsageError(
        'The first argument should be either encrypt, decrypt or generate')

  key_file_path = argv[2]
  input_file_path = argv[3] if len(argv) == 5 else None
  output_file_path = argv[4] if len(argv) == 5 else None

  # Initialise Tink
  try:
    aead.register()
  except tink.TinkError as e:
    logging.error('Error initialising Tink: %s', e)
    return 1

  if mode == 'generate':
    # [START generate-a-new-keyset]
    # Generate a new keyset
    try:
      key_template = aead.aead_key_templates.AES128_GCM
      keyset_handle = tink.KeysetHandle.generate_new(key_template)
    except tink.TinkError as e:
      logging.exception('Error creating primitive: %s', e)
      return 1
    # [END generate-a-new-keyset]

    # [START store-a-cleartext-keyset]
    with open(key_file_path, 'wt') as keyset_file:
      try:
        cleartext_keyset_handle.write(
            tink.JsonKeysetWriter(keyset_file), keyset_handle)
      except tink.TinkError as e:
        logging.exception('Error writing key: %s', e)
        return 1
    return 0
    # [END store-a-cleartext-keyset]

  # Use the input keyset to encrypt/decrypt data

  # Read the keyset into a keyset_handle
  with open(key_file_path, 'rt') as keyset_file:
    try:
      text = keyset_file.read()
      keyset_handle = cleartext_keyset_handle.read(tink.JsonKeysetReader(text))
    except tink.TinkError as e:
      logging.exception('Error reading key: %s', e)
      return 1

  # Get the primitive
  try:
    cipher = keyset_handle.primitive(aead.Aead)
  except tink.TinkError as e:
    logging.error('Error creating primitive: %s', e)
    return 1

  with open(input_file_path, 'rb') as input_file:
    input_data = input_file.read()
    if mode == 'decrypt':
      output_data = cipher.decrypt(input_data, b'envelope_example')
    elif mode == 'encrypt':
      output_data = cipher.encrypt(input_data, b'envelope_example')
    else:
      logging.error(
          'Error mode not supported. Please choose "encrypt" or "decrypt".')
      return 1

    with open(output_file_path, 'wb') as output_file:
      output_file.write(output_data)
Пример #22
0
def setUpModule():
    aead.register()
    fake_kms.register_client()
Пример #23
0
def setUpModule():
    aead.register()
    testing_servers.start('aead')
Пример #24
0
def setUpModule():
    aead.register()
    testing_servers.start('aead_consistency')
Пример #25
0
def main(argv):
    del argv  # Unused.

    associated_data = b'' if not FLAGS.associated_data else bytes(
        FLAGS.associated_data, 'utf-8')

    # Initialise Tink
    try:
        aead.register()
    except tink.TinkError as e:
        logging.error('Error initialising Tink: %s', e)
        return 1

    # Read the GCP credentials and set up a client
    try:
        gcpkms.GcpKmsClient.register_client(FLAGS.kek_uri,
                                            FLAGS.gcp_credential_path)
    except tink.TinkError as e:
        logging.error('Error initializing GCP client: %s', e)
        return 1

    # Create an AEAD primitive from the key-encryption key (KEK) for encrypting
    # Tink keysets
    try:
        handle = tink.KeysetHandle.generate_new(
            aead.aead_key_templates.create_kms_aead_key_template(
                key_uri=FLAGS.kek_uri))
        gcp_aead = handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.exception('Error creating KMS AEAD primitive: %s', e)
        return 1

    if FLAGS.mode == 'generate':
        # [START generate-a-new-keyset]
        # Generate a new keyset
        try:
            key_template = aead.aead_key_templates.AES128_GCM
            keyset_handle = tink.KeysetHandle.generate_new(key_template)
        except tink.TinkError as e:
            logging.exception('Error creating primitive: %s', e)
            return 1
        # [END generate-a-new-keyset]

        # [START encrypt-a-keyset]
        # Encrypt the keyset_handle with the remote key-encryption key (KEK)
        with open(FLAGS.keyset_path, 'wt') as keyset_file:
            try:
                keyset_handle.write(tink.JsonKeysetWriter(keyset_file),
                                    gcp_aead)
            except tink.TinkError as e:
                logging.exception('Error writing key: %s', e)
                return 1
        return 0
        # [END encrypt-a-keyset]

    # Use the keyset to encrypt/decrypt data

    # Read the encrypted keyset into a keyset_handle
    with open(FLAGS.keyset_path, 'rt') as keyset_file:
        try:
            text = keyset_file.read()
            keyset_handle = tink.KeysetHandle.read(tink.JsonKeysetReader(text),
                                                   gcp_aead)
        except tink.TinkError as e:
            logging.exception('Error reading key: %s', e)
            return 1

    # Get the primitive
    try:
        cipher = keyset_handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.error('Error creating primitive: %s', e)
        return 1

    with open(FLAGS.input_path, 'rb') as input_file:
        input_data = input_file.read()
        if FLAGS.mode == 'decrypt':
            output_data = cipher.decrypt(input_data, associated_data)
        elif FLAGS.mode == 'encrypt':
            output_data = cipher.encrypt(input_data, associated_data)
        else:
            logging.error(
                'Error mode not supported. Please choose "encrypt" or "decrypt".'
            )
            return 1

        with open(FLAGS.output_path, 'wb') as output_file:
            output_file.write(output_data)
Пример #26
0
def main(argv):
    if len(argv) != 5 and len(argv) != 7:
        raise app.UsageError(
            'Invalid arguments.\n'
            'Usage: %s generate key-file kek-uri gcp-credential-file.\n'
            'Usage: %s encrypt/decrypt key-file kek-uri gcp-credential-file '
            'input-file output-file.' % (argv[0], argv[0]))

    mode = argv[1]
    if mode not in ('encrypt', 'decrypt', 'generate'):
        raise app.UsageError(
            'The first argument should be either encrypt, decrypt or generate')

    key_file_path = argv[2]
    kek_uri = argv[3]
    gcp_credential_file = argv[4]
    input_file_path = argv[5] if len(argv) == 7 else None
    output_file_path = argv[6] if len(argv) == 7 else None

    # Initialise Tink
    try:
        aead.register()
    except tink.TinkError as e:
        logging.error('Error initialising Tink: %s', e)
        return 1

    # Read the GCP credentials and set up a client
    try:
        gcpkms.GcpKmsClient.register_client(kek_uri, gcp_credential_file)
    except tink.TinkError as e:
        logging.error('Error initializing GCP client: %s', e)
        return 1

    # Create an AEAD primitive from the key-encryption key (KEK) for encrypting
    # Tink keysets
    try:
        handle = tink.KeysetHandle.generate_new(
            aead.aead_key_templates.create_kms_aead_key_template(
                key_uri=kek_uri))
        gcp_aead = handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.exception('Error creating KMS AEAD primitive: %s', e)
        return 1

    if mode == 'generate':
        # [START generate-a-new-keyset]
        # Generate a new keyset
        try:
            key_template = aead.aead_key_templates.AES128_GCM
            keyset_handle = tink.KeysetHandle.generate_new(key_template)
        except tink.TinkError as e:
            logging.exception('Error creating primitive: %s', e)
            return 1
        # [END generate-a-new-keyset]

        # [START encrypt-a-keyset]
        # Encrypt the keyset_handle with the remote key-encryption key (KEK)
        with open(key_file_path, 'wt') as keyset_file:
            try:
                keyset_handle.write(tink.JsonKeysetWriter(keyset_file),
                                    gcp_aead)
            except tink.TinkError as e:
                logging.exception('Error writing key: %s', e)
                return 1
        return 0
        # [END encrypt-a-keyset]

    # Use the keyset to encrypt/decrypt data

    # Read the encrypted keyset into a keyset_handle
    with open(key_file_path, 'rt') as keyset_file:
        try:
            text = keyset_file.read()
            keyset_handle = tink.KeysetHandle.read(tink.JsonKeysetReader(text),
                                                   gcp_aead)
        except tink.TinkError as e:
            logging.exception('Error reading key: %s', e)
            return 1

    # Get the primitive
    try:
        cipher = keyset_handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.error('Error creating primitive: %s', e)
        return 1

    with open(input_file_path, 'rb') as input_file:
        input_data = input_file.read()
        if mode == 'decrypt':
            output_data = cipher.decrypt(input_data,
                                         b'encrypted-keyset-example')
        elif mode == 'encrypt':
            output_data = cipher.encrypt(input_data,
                                         b'encrypted-keyset-example')
        else:
            logging.error(
                'Error mode not supported. Please choose "encrypt" or "decrypt".'
            )
            return 1

        with open(output_file_path, 'wb') as output_file:
            output_file.write(output_data)
            self.public_key.encrypt(
                raw,
                OAEP(mgf=MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None)))

    def decrypt(self, raw):
        return self.private_key.decrypt(
            base64.b64decode(raw),
            OAEP(mgf=MGF1(algorithm=hashes.SHA256()),
                 algorithm=hashes.SHA256(),
                 label=None)).decode('utf-8').strip()


tink_config.register()
aead.register()
mac.register()


class AESCipher(object):
    def __init__(self, encoded_key):
        if (encoded_key == None):
            self.keyset_handle = tink.new_keyset_handle(
                aead.aead_key_templates.AES256_GCM)
        else:
            reader = tink.BinaryKeysetReader(base64.b64decode(encoded_key))
            self.keyset_handle = cleartext_keyset_handle.read(reader)
        self.key = self.keyset_handle.keyset_info()
        self.aead_primitive = self.keyset_handle.primitive(aead.Aead)

    def printKeyInfo(self):
Пример #28
0
def main(argv):
    del argv  # Unused.

    # Initialise Tink
    try:
        aead.register()
    except tink.TinkError as e:
        logging.error('Error initialising Tink: %s', e)
        return 1

    if FLAGS.mode == 'generate':
        # [START generate-a-new-keyset]
        # Generate a new keyset
        try:
            key_template = aead.aead_key_templates.AES128_GCM
            keyset_handle = tink.KeysetHandle.generate_new(key_template)
        except tink.TinkError as e:
            logging.exception('Error creating primitive: %s', e)
            return 1
        # [END generate-a-new-keyset]

        # [START store-a-cleartext-keyset]
        with open(FLAGS.keyset_path, 'wt') as keyset_file:
            try:
                cleartext_keyset_handle.write(
                    tink.JsonKeysetWriter(keyset_file), keyset_handle)
            except tink.TinkError as e:
                logging.exception('Error writing key: %s', e)
                return 1
        return 0
        # [END store-a-cleartext-keyset]

    # Use the input keyset to encrypt/decrypt data

    # Read the keyset into a keyset_handle
    with open(FLAGS.keyset_path, 'rt') as keyset_file:
        try:
            text = keyset_file.read()
            keyset_handle = cleartext_keyset_handle.read(
                tink.JsonKeysetReader(text))
        except tink.TinkError as e:
            logging.exception('Error reading key: %s', e)
            return 1

    # Get the primitive
    try:
        cipher = keyset_handle.primitive(aead.Aead)
    except tink.TinkError as e:
        logging.error('Error creating primitive: %s', e)
        return 1

    with open(FLAGS.input_path, 'rb') as input_file:
        input_data = input_file.read()
        if FLAGS.mode == 'decrypt':
            output_data = cipher.decrypt(input_data, b'envelope_example')
        elif FLAGS.mode == 'encrypt':
            output_data = cipher.encrypt(input_data, b'envelope_example')
        else:
            logging.error(
                'Error mode not supported. Please choose "encrypt" or "decrypt".'
            )
            return 1

        with open(FLAGS.output_path, 'wb') as output_file:
            output_file.write(output_data)
def setUpModule():
    aead.register()
Пример #30
0
    def __init__(self,
                 path=".",
                 server=None,
                 project_name=None,
                 show_parameter_groups=False,
                 macros=None):
        """
        Initializes a reference to a locally cloned project or to an AI Hub repository. You either need to clone a project from AI Hub first (e.g. via git commands), or point to an AI Hub repository to be able to use the methods of this class.
        
        :param path: path to the local project repository root folder. It can be a relative path from the current working directory or an absolute path. The default value points to the working directory. Set it to None to read connections from AI Hub repository (server parameter needs to be set in this case)
        :param server: Server object; required when values are encrypted or when values are injected from the AI Hub Vault
        :param project_name: name of the project to which these connections belong; if not specified, it is set to the parent directory name of the specified path parameter. Ignored if AI Hub repository connections are used
        :param show_parameter_groups: when set to True (default if False), parameter keys include the group as well in group.key format; otherwise, group is only added if there is a name collision among the keys
        :param macros: a dictionary or method defining the values for the macro injected parameters. If a connection has a prefix defined for macro keys, the prefix is added before the key. If a method is used here, it should accept connection_name and macro_name parameters, and should return the macro value for those
        """
        if not path is None:
            if not os.path.exists(path):
                raise ProjectException(
                    "Specified path does not exist: '%s'. Please make sure you have a local copy of the project at the specified path."
                    % path)
            path = os.path.abspath(path)
            # if not specified, derive project name from the directory name
            if not project_name:
                project_name = os.path.basename(path)
            path = os.path.join(path, Connections._CONNECTIONS_SUBDIR)
            if not os.path.exists(path):
                raise ProjectException(
                    "Connections directory does not exist at the specified path '%s'. Please make sure you have a local copy of the project."
                    % (os.path.dirname(path)))
        self.path = path
        aead.register()

        self.server = server
        self.project_name = project_name
        self._show_parameter_groups = show_parameter_groups
        self.macros = macros
        self.__cached_project_primitive = None
        self.__list = []

        # load connections either from legacy AI Hub repository or from project path
        if self.path is None:
            self._check_server(
                "You must either provide a project path ('path' parameter) or a Server object ('server' parameter)."
            )
            conn_json = self.server._get_connections_info()
            for c in conn_json:
                self.__list.append(
                    Connection(
                        c["location"],
                        OrderedDict(server._read_connection_info(
                            c["location"])), self))
        else:
            conn_files = glob.glob(
                os.path.join(self.path,
                             "*" + Connections._CONNECTIONS_EXTENSION))
            for z in conn_files:
                with zipfile.ZipFile(z) as zf:
                    with zf.open("Config") as f:
                        self.__list.append(
                            Connection(
                                os.path.join(Connections._CONNECTIONS_SUBDIR,
                                             os.path.basename(z)),
                                json.loads(f.read(),
                                           object_pairs_hook=OrderedDict),
                                self))
        self.__list.sort(key=lambda c: c.name)