Beispiel #1
0
  def ReadEncrypted(
      self, request: testing_api_pb2.KeysetReadEncryptedRequest,
      context: grpc.ServicerContext
  ) -> testing_api_pb2.KeysetReadEncryptedResponse:
    """Reads an encrypted keyset."""
    try:
      master_keyset_handle = cleartext_keyset_handle.read(
          tink.BinaryKeysetReader(request.master_keyset))
      master_aead = master_keyset_handle.primitive(aead.Aead)

      if request.keyset_reader_type == testing_api_pb2.KEYSET_READER_BINARY:
        reader = tink.BinaryKeysetReader(request.encrypted_keyset)
      elif request.keyset_reader_type == testing_api_pb2.KEYSET_READER_JSON:
        reader = tink.JsonKeysetReader(request.encrypted_keyset.decode('utf8'))
      else:
        raise ValueError('unknown keyset reader type')
      if request.HasField('associated_data'):
        keyset_handle = tink.read_keyset_handle_with_associated_data(
            reader, master_aead, request.associated_data.value)
      else:
        keyset_handle = tink.read_keyset_handle(reader, master_aead)

      keyset = io.BytesIO()
      cleartext_keyset_handle.write(
          tink.BinaryKeysetWriter(keyset), keyset_handle)
      return testing_api_pb2.KeysetReadEncryptedResponse(
          keyset=keyset.getvalue())
    except tink.TinkError as e:
      return testing_api_pb2.KeysetReadEncryptedResponse(err=str(e))
Beispiel #2
0
 def __init__(self, encoded_key=None):
   if encoded_key == None:
     self.keyset_handle = tink.new_keyset_handle(mac.mac_key_templates.HMAC_SHA256_256BITTAG)
   else:
     reader = tink.BinaryKeysetReader(base64.b64decode(encoded_key))
     self.keyset_handle = cleartext_keyset_handle.read(reader)
   self.mac = self.keyset_handle.primitive(mac.Mac)
Beispiel #3
0
 def test_write_encrypted_read_encrypted(self):
     encrypted_keyset = example_encrypted_keyset()
     stream = io.BytesIO()
     writer = tink.BinaryKeysetWriter(stream)
     writer.write_encrypted(encrypted_keyset)
     reader = tink.BinaryKeysetReader(stream.getvalue())
     self.assertEqual(encrypted_keyset, reader.read_encrypted())
Beispiel #4
0
    def test_from_json(self):
        keyset_servicer = services.KeysetServicer()
        json_keyset = """
        {
          "primaryKeyId": 42,
          "key": [
            {
              "keyData": {
                "typeUrl": "type.googleapis.com/google.crypto.tink.AesGcmKey",
                "keyMaterialType": "SYMMETRIC",
                "value": "AFakeTestKeyValue1234567"

              },
              "outputPrefixType": "TINK",
              "keyId": 42,
              "status": "ENABLED"
            }
          ]
        }"""
        request = testing_api_pb2.KeysetFromJsonRequest(
            json_keyset=json_keyset)
        response = keyset_servicer.FromJson(request, self._ctx)
        self.assertEqual(response.WhichOneof('result'), 'keyset')
        keyset = tink.BinaryKeysetReader(response.keyset).read()
        self.assertEqual(keyset.primary_key_id, 42)
        self.assertLen(keyset.key, 1)
Beispiel #5
0
def public_keyset_handle(private_keyset_handle) -> tink.KeysetHandle:
    """Generates a public keyset handle from a private one."""
    with tempfile.TemporaryDirectory() as tmpdir:
        cli_path = os.path.join(_tools_path(), _TINKEY_CLI_PATH)
        private_keyset_filename = os.path.join(tmpdir, 'private_keyset_file')
        with open(private_keyset_filename, 'wb') as f:
            cleartext_keyset_handle.write(tink.BinaryKeysetWriter(f),
                                          private_keyset_handle)
        public_keyset_filename = os.path.join(tmpdir, 'public_keyset_file')
        unused_return_value = subprocess.check_output([
            cli_path,
            'create-public-keyset',
            '--in-format',
            'BINARY',
            '--in',
            private_keyset_filename,
            '--out-format',
            'BINARY',
            '--out',
            public_keyset_filename,
        ])
        with open(public_keyset_filename, 'rb') as f:
            public_keyset_data = f.read()
        return cleartext_keyset_handle.read(
            tink.BinaryKeysetReader(public_keyset_data))
Beispiel #6
0
def new_keyset_handle(stub: testing_api_pb2_grpc.KeysetStub,
                      key_template: tink_pb2.KeyTemplate) -> tink.KeysetHandle:
    gen_request = testing_api_pb2.KeysetGenerateRequest(
        template=key_template.SerializeToString())
    gen_response = stub.Generate(gen_request)
    if gen_response.err:
        raise tink.TinkError(gen_response.err)
    return cleartext_keyset_handle.read(
        tink.BinaryKeysetReader(gen_response.keyset))
 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)
Beispiel #8
0
  def test_read_no_secret(self):
    private_handle = tink.new_keyset_handle(
        hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM)
    public_handle = private_handle.public_keyset_handle()

    output_stream_pub = io.BytesIO()
    writer = tink.BinaryKeysetWriter(output_stream_pub)
    writer.write(public_handle._keyset)

    output_stream_priv = io.BytesIO()
    writer = tink.BinaryKeysetWriter(output_stream_priv)
    writer.write(private_handle._keyset)

    reader = tink.BinaryKeysetReader(output_stream_pub.getvalue())
    tink.read_no_secret_keyset_handle(reader)

    reader = tink.BinaryKeysetReader(output_stream_priv.getvalue())
    with self.assertRaises(core.TinkError):
      tink.read_no_secret_keyset_handle(reader)
Beispiel #9
0
def public_keyset_handle(
        stub: testing_api_pb2_grpc.KeysetStub,
        private_keyset_handle: tink.KeysetHandle) -> tink.KeysetHandle:
    request = testing_api_pb2.KeysetPublicRequest(
        private_keyset=_keyset(private_keyset_handle))
    response = stub.Public(request)
    if response.err:
        raise tink.TinkError(response.err)
    return cleartext_keyset_handle.read(
        tink.BinaryKeysetReader(response.public_keyset))
Beispiel #10
0
 def test_read_encrypted(self):
     encrypted_keyset = tink_pb2.EncryptedKeyset()
     encrypted_keyset.encrypted_keyset = b'c29tZSBjaXBoZXJ0ZXh0IHdpdGgga2V5c2V0'
     encrypted_keyset.keyset_info.primary_key_id = 42
     key_info = encrypted_keyset.keyset_info.key_info.add()
     key_info.type_url = 'type.googleapis.com/google.crypto.tink.AesGcmKey'
     key_info.output_prefix_type = tink_pb2.TINK
     key_info.key_id = 42
     key_info.status = tink_pb2.ENABLED
     reader = tink.BinaryKeysetReader(encrypted_keyset.SerializeToString())
     self.assertEqual(encrypted_keyset, reader.read_encrypted())
Beispiel #11
0
 def test_write_encrypted_with_mismatched_associated_data(self):
   handle = tink.new_keyset_handle(mac.mac_key_templates.HMAC_SHA256_128BITTAG)
   # Encrypt the keyset with Aead.
   master_key_aead = _master_key_aead()
   output_stream = io.BytesIO()
   writer = tink.BinaryKeysetWriter(output_stream)
   handle.write_with_associated_data(writer, master_key_aead, b'01')
   reader = tink.BinaryKeysetReader(output_stream.getvalue())
   with self.assertRaises(core.TinkError):
     tink.read_keyset_handle_with_associated_data(reader, master_key_aead,
                                                  b'02')
Beispiel #12
0
 def test_write_read(self):
     handle = tink.new_keyset_handle(
         mac.mac_key_templates.HMAC_SHA256_128BITTAG)
     output_stream = io.BytesIO()
     writer = tink.BinaryKeysetWriter(output_stream)
     cleartext_keyset_handle.write(writer, handle)
     reader = tink.BinaryKeysetReader(output_stream.getvalue())
     handle2 = cleartext_keyset_handle.read(reader)
     # Check that handle2 has the same primitive as handle.
     handle2.primitive(mac.Mac).verify_mac(
         handle.primitive(mac.Mac).compute_mac(b'data'), b'data')
Beispiel #13
0
 def test_write_encrypted(self):
   handle = tink.new_keyset_handle(mac.mac_key_templates.HMAC_SHA256_128BITTAG)
   # Encrypt the keyset with Aead.
   master_key_aead = _master_key_aead()
   output_stream = io.BytesIO()
   writer = tink.BinaryKeysetWriter(output_stream)
   handle.write(writer, master_key_aead)
   reader = tink.BinaryKeysetReader(output_stream.getvalue())
   handle2 = tink.read_keyset_handle(reader, master_key_aead)
   # Check that handle2 has the same primitive as handle.
   handle2.primitive(mac.Mac).verify_mac(
       handle.primitive(mac.Mac).compute_mac(b'data'), b'data')
Beispiel #14
0
 def __init__(self, encoded_key, key_uri=None):
     self.gcp_aead = None
     if key_uri != None:
         gcp_client = gcpkms.GcpKmsClient(key_uri=key_uri,
                                          credentials_path="")
         self.gcp_aead = gcp_client.get_aead(key_uri)
         if (encoded_key == None):
             self.keyset_handle = tink.new_keyset_handle(
                 mac.mac_key_templates.HMAC_SHA256_256BITTAG)
         else:
             reader = tink.BinaryKeysetReader(base64.b64decode(encoded_key))
             self.keyset_handle = tink.KeysetHandle.read(
                 reader, self.gcp_aead)
     else:
         if (encoded_key == None):
             self.keyset_handle = tink.new_keyset_handle(
                 mac.mac_key_templates.HMAC_SHA256_256BITTAG)
         else:
             reader = tink.BinaryKeysetReader(base64.b64decode(encoded_key))
             self.keyset_handle = cleartext_keyset_handle.read(reader)
     self.mac = self.keyset_handle.primitive(mac.Mac)
Beispiel #15
0
 def ComputeMac(
     self, request: testing_api_pb2.ComputeMacRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.ComputeMacResponse:
   """Computes a MAC."""
   try:
     keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.keyset))
     p = keyset_handle.primitive(mac.Mac)
     mac_value = p.compute_mac(request.data)
     return testing_api_pb2.ComputeMacResponse(mac_value=mac_value)
   except tink.TinkError as e:
     return testing_api_pb2.ComputeMacResponse(err=str(e))
Beispiel #16
0
 def test_read(self):
   keyset = tink_pb2.Keyset()
   keyset.primary_key_id = 42
   key = keyset.key.add()
   key.key_data.type_url = 'type.googleapis.com/google.crypto.tink.AesGcmKey'
   key.key_data.key_material_type = tink_pb2.KeyData.SYMMETRIC
   key.key_data.value = b'GhCS/1+ejWpx68NfGt6ziYHd'
   key.output_prefix_type = tink_pb2.TINK
   key.key_id = 42
   key.status = tink_pb2.ENABLED
   reader = tink.BinaryKeysetReader(keyset.SerializeToString())
   self.assertEqual(keyset, reader.read())
Beispiel #17
0
 def Decrypt(
     self, request: testing_api_pb2.AeadDecryptRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.PlaintextResponse:
   """Decrypts a message."""
   try:
     keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.keyset))
     p = keyset_handle.primitive(aead.Aead)
     plaintext = p.decrypt(request.ciphertext, request.associated_data)
     return testing_api_pb2.PlaintextResponse(plaintext=plaintext)
   except tink.TinkError as e:
     return testing_api_pb2.PlaintextResponse(err=str(e))
Beispiel #18
0
 def Verify(
     self, request: testing_api_pb2.SignatureVerifyRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.SignatureVerifyResponse:
   """Verifies a signature."""
   try:
     public_keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.public_keyset))
     p = public_keyset_handle.primitive(signature.PublicKeyVerify)
     p.verify(request.signature, request.data)
     return testing_api_pb2.SignatureVerifyResponse()
   except tink.TinkError as e:
     return testing_api_pb2.SignatureVerifyResponse(err=str(e))
Beispiel #19
0
 def Compute(
     self, request: testing_api_pb2.PrfSetComputeRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.PrfSetComputeResponse:
   """Computes the output of one PRF."""
   try:
     keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.keyset))
     f = keyset_handle.primitive(prf.PrfSet).all()[request.key_id]
     return testing_api_pb2.PrfSetComputeResponse(
         output=f.compute(request.input_data, request.output_length))
   except tink.TinkError as e:
     return testing_api_pb2.PrfSetComputeResponse(err=str(e))
Beispiel #20
0
def generate_keyset(key_template) -> tink_pb2.Keyset:
    """Generates a keyset handle from a key templates."""
    with tempfile.TemporaryDirectory() as tmpdir:
        keyset_filename = os.path.join(tmpdir, 'keyset_file')
        cli_path = os.path.join(_tools_path(), _TINKEY_CLI_PATH)
        unused_return_value = subprocess.check_output([
            cli_path, 'create-keyset', '--key-template', key_template,
            '--out-format', 'BINARY', '--out', keyset_filename
        ])
        with open(keyset_filename, 'rb') as f:
            keyset_data = f.read()
        return tink.BinaryKeysetReader(keyset_data).read()
Beispiel #21
0
 def Decrypt(
     self, request: testing_api_pb2.HybridDecryptRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.HybridDecryptResponse:
   """Decrypts a message."""
   try:
     private_keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.private_keyset))
     p = private_keyset_handle.primitive(hybrid.HybridDecrypt)
     plaintext = p.decrypt(request.ciphertext, request.context_info)
     return testing_api_pb2.HybridDecryptResponse(plaintext=plaintext)
   except tink.TinkError as e:
     return testing_api_pb2.HybridDecryptResponse(err=str(e))
Beispiel #22
0
 def VerifyMac(
     self, request: testing_api_pb2.VerifyMacRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.VerifyMacResponse:
   """Verifies a MAC value."""
   try:
     keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.keyset))
     p = keyset_handle.primitive(mac.Mac)
     p.verify_mac(request.mac_value, request.data)
     return testing_api_pb2.VerifyMacResponse()
   except tink.TinkError as e:
     return testing_api_pb2.VerifyMacResponse(err=str(e))
Beispiel #23
0
 def ToJwkSet(
         self, request: testing_api_pb2.JwtToJwkSetRequest,
         context: grpc.ServicerContext
 ) -> testing_api_pb2.JwtToJwkSetResponse:
     """Converts a Tink Keyset with JWT keys into a JWK set."""
     try:
         keyset_handle = cleartext_keyset_handle.read(
             tink.BinaryKeysetReader(request.keyset))
         jwk_set = jwt.jwk_set_from_public_keyset_handle(keyset_handle)
         return testing_api_pb2.JwtToJwkSetResponse(jwk_set=jwk_set)
     except tink.TinkError as e:
         return testing_api_pb2.JwtToJwkSetResponse(err=str(e))
Beispiel #24
0
 def Sign(
     self, request: testing_api_pb2.SignatureSignRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.SignatureSignResponse:
   """Signs a message."""
   try:
     private_keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.private_keyset))
     p = private_keyset_handle.primitive(signature.PublicKeySign)
     signature_value = p.sign(request.data)
     return testing_api_pb2.SignatureSignResponse(signature=signature_value)
   except tink.TinkError as e:
     return testing_api_pb2.SignatureSignResponse(err=str(e))
Beispiel #25
0
    def __init__(self, encoded_key, key_uri=None):
        self.gcp_aead = None
        if key_uri != None:
            gcp_client = gcpkms.GcpKmsClient(key_uri=key_uri,
                                             credentials_path="")
            self.gcp_aead = gcp_client.get_aead(key_uri)
            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 = tink.KeysetHandle.read(
                    reader, self.gcp_aead)
        else:
            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)
Beispiel #26
0
def encryption_machine(msg):
    # Register all deterministic AEAD primitives
    daead.register()
    # Get the secret key from the file
    keyset = open('keys.txt', 'rb').read()
    reader = tink.BinaryKeysetReader(keyset)
    secret_key = tink.cleartext_keyset_handle.read(reader)
    associated_data = b'context'
    # Get the primitive
    daead_primitive = secret_key.primitive(daead.DeterministicAead)
    secret_key = daead_primitive
    # Use the primitive.
    cipherText = secret_key.encrypt_deterministically(msg.encode("utf-8"), associated_data)
    return cipherText
Beispiel #27
0
 def PublicKeySignAndEncode(
     self, request: testing_api_pb2.JwtSignRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.JwtSignResponse:
   """Computes a signed compact JWT token."""
   try:
     keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.keyset))
     p = keyset_handle.primitive(jwt.JwtPublicKeySign)
     raw_jwt = raw_jwt_from_proto(request.raw_jwt)
     signed_compact_jwt = p.sign_and_encode(raw_jwt)
     return testing_api_pb2.JwtSignResponse(
         signed_compact_jwt=signed_compact_jwt)
   except tink.TinkError as e:
     return testing_api_pb2.JwtSignResponse(err=str(e))
Beispiel #28
0
 def PublicKeyVerifyAndDecode(
     self, request: testing_api_pb2.JwtVerifyRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.JwtVerifyResponse:
   """Verifies the validity of the signed compact JWT token."""
   try:
     keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.keyset))
     validator = validator_from_proto(request.validator)
     p = keyset_handle.primitive(jwt.JwtPublicKeyVerify)
     verified_jwt = p.verify_and_decode(request.signed_compact_jwt, validator)
     return testing_api_pb2.JwtVerifyResponse(
         verified_jwt=verifiedjwt_to_proto(verified_jwt))
   except tink.TinkError as e:
     return testing_api_pb2.JwtVerifyResponse(err=str(e))
Beispiel #29
0
 def ToJson(
     self, request: testing_api_pb2.KeysetToJsonRequest,
     context: grpc.ServicerContext) -> testing_api_pb2.KeysetToJsonResponse:
   """Converts a keyset from binary to JSON format."""
   try:
     keyset_handle = cleartext_keyset_handle.read(
         tink.BinaryKeysetReader(request.keyset))
     json_keyset = io.StringIO()
     cleartext_keyset_handle.write(
         tink.JsonKeysetWriter(json_keyset), keyset_handle)
     return testing_api_pb2.KeysetToJsonResponse(
         json_keyset=json_keyset.getvalue())
   except tink.TinkError as e:
     return testing_api_pb2.KeysetToJsonResponse(err=str(e))
Beispiel #30
0
 def EncryptDeterministically(
     self, request: testing_api_pb2.DeterministicAeadEncryptRequest,
     context: grpc.ServicerContext
 ) -> testing_api_pb2.DeterministicAeadEncryptResponse:
     """Encrypts a message."""
     try:
         keyset_handle = cleartext_keyset_handle.read(
             tink.BinaryKeysetReader(request.keyset))
         p = keyset_handle.primitive(daead.DeterministicAead)
         ciphertext = p.encrypt_deterministically(request.plaintext,
                                                  request.associated_data)
         return testing_api_pb2.DeterministicAeadEncryptResponse(
             ciphertext=ciphertext)
     except tink.TinkError as e:
         return testing_api_pb2.DeterministicAeadEncryptResponse(err=str(e))