• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2019 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Deterministic AEAD wrapper."""
16
17from typing import Type
18from absl import logging
19
20from tink import core
21from tink.daead import _deterministic_aead
22
23
24class _WrappedDeterministicAead(_deterministic_aead.DeterministicAead):
25  """Implements DeterministicAead for a set of DeterministicAead primitives."""
26
27  def __init__(self, pset: core.PrimitiveSet):
28    self._primitive_set = pset
29
30  def encrypt_deterministically(self, plaintext: bytes,
31                                associated_data: bytes) -> bytes:
32    primary = self._primitive_set.primary()
33    return primary.identifier + primary.primitive.encrypt_deterministically(
34        plaintext, associated_data)
35
36  def decrypt_deterministically(self, ciphertext: bytes,
37                                associated_data: bytes) -> bytes:
38    if len(ciphertext) > core.crypto_format.NON_RAW_PREFIX_SIZE:
39      prefix = ciphertext[:core.crypto_format.NON_RAW_PREFIX_SIZE]
40      ciphertext_no_prefix = ciphertext[core.crypto_format.NON_RAW_PREFIX_SIZE:]
41      for entry in self._primitive_set.primitive_from_identifier(prefix):
42        try:
43          return entry.primitive.decrypt_deterministically(ciphertext_no_prefix,
44                                                           associated_data)
45        except core.TinkError as e:
46          logging.info(
47              'ciphertext prefix matches a key, but cannot decrypt: %s', e)
48    # Let's try all RAW keys.
49    for entry in self._primitive_set.raw_primitives():
50      try:
51        return entry.primitive.decrypt_deterministically(ciphertext,
52                                                         associated_data)
53      except core.TinkError as e:
54        pass
55    # nothing works.
56    raise core.TinkError('Decryption failed.')
57
58
59class DeterministicAeadWrapper(
60    core.PrimitiveWrapper[_deterministic_aead.DeterministicAead,
61                          _deterministic_aead.DeterministicAead]):
62  """DeterministicAeadWrapper is a PrimitiveWrapper for DeterministicAead.
63
64  The created primitive works with a keyset (rather than a single key). To
65  encrypt a plaintext, it uses the primary key in the keyset, and prepends to
66  the ciphertext a certain prefix associated with the primary key. To decrypt,
67  the primitive uses the prefix of the ciphertext to efficiently select the
68  right key in the set. If the keys associated with the prefix do not work, the
69  primitive tries all keys with OutputPrefixType RAW.
70  """
71
72  def wrap(
73      self, pset: core.PrimitiveSet) -> _deterministic_aead.DeterministicAead:
74    return _WrappedDeterministicAead(pset)
75
76  def primitive_class(self) -> Type[_deterministic_aead.DeterministicAead]:
77    return _deterministic_aead.DeterministicAead
78
79  def input_primitive_class(
80      self) -> Type[_deterministic_aead.DeterministicAead]:
81    return _deterministic_aead.DeterministicAead
82