def read_keyset(keyset_filename): """Load a keyset from a file. Args: keyset_filename: A path to a keyset file Returns: A KeysetHandle of the file's keyset Raises: TinkError: if the file is not valid IOError: if the file does not exist """ with open(keyset_filename, 'rb') as keyset_file: text = keyset_file.read() keyset = tink.KeysetHandle(tink.BinaryKeysetReader(text).read()) return keyset
def test_instantiation__raises_error(self): with self.assertRaises(core.TinkError): tink.KeysetHandle()
def main(argv): if len(argv) not in (3, 4): raise app.UsageError( 'Expected 2 or 3 arguments, got %d.\n' 'Usage: %s keyset-file data-file [expected-code-file]' % (len(argv) - 1, argv[0])) keyset_filename = argv[1] data_filename = argv[2] expected_code_filename = argv[3] if len(argv) == 4 else None if expected_code_filename is not None: with open(expected_code_filename, 'rb') as expected_code_file: expected_code_hex = expected_code_file.read().strip() logging.info( 'Using keyset from file %s to verify file %s against expected code %s', keyset_filename, data_filename, expected_code_hex.decode('utf-8')) else: expected_code_hex = None logging.info('Using keyset from file %s to verify file %s', keyset_filename, data_filename) # Initialise Tink. try: tink.tink_config.register() except tink.TinkError as e: logging.error('Error initialising Tink: %s', e) return 1 # Read the keyset. with open(keyset_filename, 'rb') as keyset_file: try: text = keyset_file.read() keyset = tink.KeysetHandle(tink.JsonKeysetReader(text).read()) except tink.TinkError as e: logging.error('Error reading key: %s', e) return 1 # Get the primitive. try: cipher = keyset.primitive(tink.Mac) except tink.TinkError as e: logging.error('Error creating primitive: %s', e) return 1 # Compute the MAC. with open(data_filename, 'rb') as data_file: data = data_file.read() if expected_code_hex is None: code = cipher.compute_mac(data) logging.info('MAC output is %s', binascii.hexlify(code).decode('utf-8')) return 0 try: expected_code = binascii.unhexlify(expected_code_hex) except binascii.Error as e: logging.error('Error reading expected code: %s', e) return 1 try: cipher.verify_mac(expected_code, data) logging.info('MAC outputs matched. Success!') return 0 except tink.TinkError as e: logging.info('MAC outputs did not match!') code = binascii.hexlify(cipher.compute_mac(data)).decode('utf-8') logging.info('Actual MAC output is %s', code) return 1
def test_instantiation(self): with self.assertRaisesRegex(core.TinkError, 'cannot be instantiated'): tink.KeysetHandle()