1# Copyright 2022 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"""Example to showcase how to obtain and use a primitive from a keyset.""" 15# [START tink_walkthrough_obtain_and_use_a_primitive] 16import tink 17from tink import aead 18 19 20def AeadEncrypt(keyset_handle: tink.KeysetHandle, plaintext: bytes, 21 associated_data: bytes) -> bytes: 22 """AEAD encrypts a plaintext with the primary key in keyset_handle. 23 24 Prerequisites for this example: 25 - Register AEAD implementations of Tink. 26 - Create a keyset and get a handle to it. 27 28 Args: 29 keyset_handle: Keyset handle containing at least an AEAD key. 30 plaintext: Plaintext to encrypt. 31 associated_data: Associated data. 32 33 Returns: 34 The resulting ciphertext 35 36 Raises: 37 tink.TinkError in case of errors. 38 """ 39 # To facilitate key rotation, `primitive` returns an Aead primitive that 40 # "wraps" multiple Aead primitives in the keyset. It uses the primary key to 41 # encrypt; For the key we use in this example, the first 5 bytes of the 42 # ciphertext contain the ID of the encryption key. 43 aead_primitive = keyset_handle.primitive(aead.Aead) 44 return aead_primitive.encrypt(plaintext, associated_data) 45 46 47def AeadDecrypt(keyset_handle: tink.KeysetHandle, ciphertext: bytes, 48 associated_data: bytes) -> bytes: 49 """AEAD decrypts a ciphertext with the corresponding key in keyset_handle. 50 51 Prerequisites for this example: 52 - Register AEAD implementations of Tink. 53 - Create a keyset and get a handle to it. 54 - Encrypt a plaintext with an AEAD primitive in keyset_handle. 55 56 Args: 57 keyset_handle: Keyset handle containing at least an AEAD key. 58 ciphertext: Tink ciphertext to decrypt. 59 associated_data: Associated data. 60 61 Returns: 62 The resulting ciphertext 63 64 Raises: 65 tink.TinkError in case of errors. 66 """ 67 # To facilitate key rotation, `primitive` returns an Aead primitive that 68 # "wraps" multiple Aead primitives in the keyset. In this example, it uses the 69 # key that was used to encrypt looking it up by key ID; the ID is contained in 70 # the first 5 bytes of the ciphertext. 71 aead_primitive = keyset_handle.primitive(aead.Aead) 72 return aead_primitive.decrypt(ciphertext, associated_data) 73 74 75# [END tink_walkthrough_obtain_and_use_a_primitive] 76