def test_encrypt_decrypt_with_primary_key_succeeds(self): private_handle_with_primary = cleartext_keyset_handle.read( tink.JsonKeysetReader(PRIVATE_KEYSET_WITH_PRIMARY)) public_handle_with_primary = cleartext_keyset_handle.read( tink.JsonKeysetReader(PUBLIC_KEYSET_WITH_PRIMARY)) dec = private_handle_with_primary.primitive(hybrid.HybridDecrypt) enc = public_handle_with_primary.primitive(hybrid.HybridEncrypt) ciphertext = enc.encrypt(b'plaintext', b'context') self.assertEqual(dec.decrypt(ciphertext, b'context'), b'plaintext')
def test_encrypt_decrypt_without_primary_key_fails(self): with self.assertRaises(tink.TinkError): cleartext_keyset_handle.read( tink.JsonKeysetReader(PRIVATE_KEYSET_WITHOUT_PRIMARY)) # Currently, the public keyset only fails when 'encrypt' is called. # TODO(b/228140127): It would be preferable that it fails earlier. public_handle_without_primary = cleartext_keyset_handle.read( tink.JsonKeysetReader(PUBLIC_KEYSET_WITHOUT_PRIMARY)) enc_without_primary = public_handle_without_primary.primitive( hybrid.HybridEncrypt) with self.assertRaises(tink.TinkError): enc_without_primary.encrypt(b'plaintext', b'context')
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))
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))
def main(argv): del argv # Unused. # Initialise Tink try: jwt.register_jwt_signature() except tink.TinkError as e: logging.exception('Error initialising Tink: %s', e) return 1 # Read the keyset into a KeysetHandle 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 keyset: %s', e) return 1 # Export Public Keyset as JWK set public_jwk_set = jwt.jwk_set_from_public_keyset_handle( keyset_handle.public_keyset_handle()) with open(FLAGS.public_jwk_set_path, 'wt') as public_jwk_set_file: public_jwk_set_file.write(public_jwk_set) logging.info('The public JWK set has been written to %s', FLAGS.public_jwk_set_path)
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)
def main(argv): del argv context_info = b'' if not FLAGS.context_info else bytes( FLAGS.context_info, 'utf-8') # Initialise Tink. try: hybrid.register() except tink.TinkError: logging.exception('Error initialising Tink.') return 1 # Read the keyset into a keyset_handle. with open(FLAGS.keyset_path, 'rt') as keyset_file: text = keyset_file.read() try: keyset_handle = cleartext_keyset_handle.read(tink.JsonKeysetReader(text)) except tink.TinkError: logging.exception('Error reading key.') return 1 # Get the primitive. try: primitive = keyset_handle.primitive(hybrid.HybridDecrypt) except tink.TinkError: logging.exception( 'Error creating hybrid decrypt primitive from keyset.') return 1 with open(FLAGS.input_path, 'rb') as input_file: with open(FLAGS.output_path, 'wb') as output_file: data = input_file.read() plaintext = primitive.decrypt(data, context_info) output_file.write(plaintext)
def main(argv): del argv # Unused. # Initialise Tink try: jwt.register_jwt_signature() except tink.TinkError as e: logging.exception('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 keyset: %s', e) return 1 now = datetime.datetime.now(tz=datetime.timezone.utc) if FLAGS.mode == 'sign': # Get the JwtPublicKeySign primitive try: jwt_sign = keyset_handle.primitive(jwt.JwtPublicKeySign) except tink.TinkError as e: logging.exception('Error creating JwtPublicKeySign: %s', e) return 1 # Create token raw_jwt = jwt.new_raw_jwt(subject=FLAGS.subject, expiration=now + datetime.timedelta(seconds=100)) token = jwt_sign.sign_and_encode(raw_jwt) with open(FLAGS.token_path, 'wt') as token_file: token_file.write(token) logging.info('Token has been written to %s', FLAGS.token_path) return 0 # Get the JwtPublicKeyVerify primitive try: jwt_verify = keyset_handle.primitive(jwt.JwtPublicKeyVerify) except tink.TinkError as e: logging.exception('Error creating JwtPublicKeyVerify: %s', e) return 1 # Verify token with open(FLAGS.token_path, 'rt') as token_file: token = token_file.read() validator = jwt.new_validator(expected_subject=FLAGS.subject) try: verified_jwt = jwt_verify.verify_and_decode(token, validator) expires_in = verified_jwt.expiration() - now logging.info('Token is valid and expires in %s seconds', expires_in.seconds) return 0 except tink.TinkError as e: logging.info('JWT verification failed: %s', e) return 1
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 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 main(argv): del argv # Unused mode = FLAGS.mode if mode not in ('encrypt', 'decrypt'): logging.error('Incorrect mode. Please select "encrypt" or "decrypt".') return 1 context_info = b'' if not FLAGS.context_info else bytes( FLAGS.context_info, 'utf-8') # Initialise Tink try: hybrid.register() except tink.TinkError as e: logging.exception('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 with open(FLAGS.input_path, 'rb') as input_file: data = input_file.read() if mode == 'encrypt': # Get the primitive try: primitive = keyset_handle.primitive(hybrid.HybridEncrypt) except tink.TinkError as e: logging.exception( 'Error creating hybrid encrypt primitive from keyset: %s', e) return 1 # Encrypt data with open(FLAGS.output_path, 'wb') as output_file: ciphertext = primitive.encrypt(data, context_info) output_file.write(ciphertext) return 0 # Get the primitive try: primitive = keyset_handle.primitive(hybrid.HybridDecrypt) except tink.TinkError as e: logging.exception( 'Error creating hybrid encrypt primitive from keyset: %s', e) return 1 # Decrypt data with open(FLAGS.output_path, 'wb') as output_file: plaintext = primitive.decrypt(data, context_info) output_file.write(plaintext) return 0
def _get_project_primitive(self): # project primitive is not expected to change - initialized once, when first needed if self.__cached_project_primitive == None: response = self.server._get_project_info(self.project_name) content = json.dumps(response["secret"]) reader = JsonKeysetReader(content) keyset_handle = cleartext_keyset_handle.read(reader) self.__cached_project_primitive = keyset_handle.primitive( aead.Aead) return self.__cached_project_primitive
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))
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')
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))
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))
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))
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))
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))
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))
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))
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: daead.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(daead.DeterministicAead) 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_deterministically( input_data, associated_data) elif mode == 'encrypt': output_data = cipher.encrypt_deterministically( 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)
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))
def FromJson( self, request: testing_api_pb2.KeysetFromJsonRequest, context: grpc.ServicerContext) -> testing_api_pb2.KeysetFromJsonResponse: """Converts a keyset from JSON to binary format.""" try: keyset_handle = cleartext_keyset_handle.read( tink.JsonKeysetReader(request.json_keyset)) keyset = io.BytesIO() cleartext_keyset_handle.write( tink.BinaryKeysetWriter(keyset), keyset_handle) return testing_api_pb2.KeysetFromJsonResponse(keyset=keyset.getvalue()) except tink.TinkError as e: return testing_api_pb2.KeysetFromJsonResponse(err=str(e))
def main(argv): del argv # Unused. # Initialise Tink. try: mac.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.error('Error reading key: %s', e) return 1 # Get the primitive. try: cipher = keyset_handle.primitive(mac.Mac) except tink.TinkError as e: logging.error('Error creating primitive: %s', e) return 1 with open(FLAGS.data_path, 'rb') as data_file: data = data_file.read() if FLAGS.mode == 'compute': # Compute the MAC. code = cipher.compute_mac(data) with open(FLAGS.mac_path, 'wb') as mac_file: mac_file.write(binascii.hexlify(code)) return 0 with open(FLAGS.mac_path, 'rb') as mac_file: try: expected_mac = binascii.unhexlify(mac_file.read().strip()) except binascii.Error as e: logging.exception('Error reading expected code: %s', e) return 1 try: cipher.verify_mac(expected_mac, data) logging.info('MAC verification succeeded.') return 0 except tink.TinkError as e: logging.info('MAC verification failed.') return 1
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))
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))
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))
def WriteEncrypted( self, request: testing_api_pb2.KeysetWriteEncryptedRequest, context: grpc.ServicerContext ) -> testing_api_pb2.KeysetWriteEncryptedResponse: """Writes an encrypted keyset.""" try: master_keyset_handle = cleartext_keyset_handle.read( tink.BinaryKeysetReader(request.master_keyset)) keyset_handle = cleartext_keyset_handle.read( tink.BinaryKeysetReader(request.keyset)) master_aead = master_keyset_handle.primitive(aead.Aead) encrypted_keyset = io.BytesIO() if request.HasField('associated_data'): keyset_handle.write_with_associated_data( tink.BinaryKeysetWriter(encrypted_keyset), master_aead, request.associated_data.value) else: keyset_handle.write(tink.BinaryKeysetWriter(encrypted_keyset), master_aead) return testing_api_pb2.KeysetWriteEncryptedResponse( encrypted_keyset=encrypted_keyset.getvalue()) except tink.TinkError as e: return testing_api_pb2.KeysetWriteEncryptedResponse(err=str(e))
def KeyIds( self, request: testing_api_pb2.PrfSetKeyIdsRequest, context: grpc.ServicerContext) -> testing_api_pb2.PrfSetKeyIdsResponse: """Returns all key IDs and the primary key ID.""" try: keyset_handle = cleartext_keyset_handle.read( tink.BinaryKeysetReader(request.keyset)) p = keyset_handle.primitive(prf.PrfSet) prfs = p.all() response = testing_api_pb2.PrfSetKeyIdsResponse() response.output.primary_key_id = p.primary_id() response.output.key_id.extend(prfs.keys()) return response except tink.TinkError as e: return testing_api_pb2.PrfSetKeyIdsResponse(err=str(e))