Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def write(self, keyset: tink_pb2.Keyset) -> None:
if not isinstance(keyset, tink_pb2.Keyset):
raise tink_error.TinkError('invalid keyset.')
json_keyset = json_format.MessageToJson(keyset)
# TODO(b/141106504) Needed for python 2.7 compatibility. StringIO expects
# unicode, but MessageToJson outputs UTF-8.
if isinstance(json_keyset, bytes):
json_keyset = json_keyset.decode('utf-8')
self._io_stream.write(json_keyset)
self._io_stream.flush()
def _validate_keyset(keyset: tink_pb2.Keyset):
"""Raises tink_error.TinkError if keyset is not valid."""
for key in keyset.key:
if key.status != tink_pb2.DESTROYED:
_validate_key(key)
num_non_destroyed_keys = sum(
1 for key in keyset.key if key.status != tink_pb2.DESTROYED)
num_non_public_key_material = sum(
1 for key in keyset.key
if key.key_data.key_material_type != tink_pb2.KeyData.ASYMMETRIC_PUBLIC)
num_primary_keys = sum(
1 for key in keyset.key
if key.status == tink_pb2.ENABLED and key.key_id == keyset.primary_key_id)
if num_non_destroyed_keys == 0:
raise tink_error.TinkError('empty keyset')
if num_primary_keys > 1:
raise tink_error.TinkError('keyset contains multiple primary keys')
if num_primary_keys == 0 and num_non_public_key_material > 0:
raise tink_error.TinkError('keyset does not contain a valid primary key')
def write_encrypted(self, encrypted_keyset: tink_pb2.EncryptedKeyset) -> None:
if not isinstance(encrypted_keyset, tink_pb2.EncryptedKeyset):
raise tink_error.TinkError('invalid encrypted keyset.')
json_keyset = json_format.MessageToJson(encrypted_keyset)
# TODO(b/141106504) Needed for python 2.7 compatibility. StringIO expects
# unicode, but MessageToJson outputs UTF-8.
if isinstance(json_keyset, bytes):
json_keyset = json_keyset.decode('utf-8')
self._io_stream.write(json_keyset)
self._io_stream.flush()
def _validate_key(key: tink_pb2.Keyset.Key):
"""Raises tink_error.TinkError if key is not valid."""
if not key.HasField('key_data'):
raise tink_error.TinkError('key {} has no key data'.format(key.key_id))
if key.output_prefix_type == tink_pb2.UNKNOWN_PREFIX:
raise tink_error.TinkError('key {} has unknown prefix'.format(key.key_id))
if key.status == tink_pb2.UNKNOWN_STATUS:
raise tink_error.TinkError('key {} has unknown status'.format(key.key_id))