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"""A minimal example for using the deterministic AEAD API.""" 15# [START deterministic-aead-basic-example] 16import tink 17from tink import cleartext_keyset_handle 18from tink import daead 19 20 21def example(): 22 """Encrypt and decrypt using deterministic AEAD.""" 23 # Register the deterministic AEAD key manager. This is needed to create a 24 # DeterministicAead primitive later. 25 daead.register() 26 27 # A keyset created with "tinkey create-keyset --key-template=AES256_SIV". Note 28 # that this keyset has the secret key information in cleartext. 29 keyset = r"""{ 30 "key": [{ 31 "keyData": { 32 "keyMaterialType": 33 "SYMMETRIC", 34 "typeUrl": 35 "type.googleapis.com/google.crypto.tink.AesSivKey", 36 "value": 37 "EkAl9HCMmKTN1p3V186uhZpJQ+tivyc4IKyE+opg6SsEbWQ/WesWHzwCRrlgRuxdaggvgMzwWhjPnkk9gptBnGLK" 38 }, 39 "keyId": 1919301694, 40 "outputPrefixType": "TINK", 41 "status": "ENABLED" 42 }], 43 "primaryKeyId": 1919301694 44 }""" 45 46 # Create a keyset handle from the cleartext keyset in the previous 47 # step. The keyset handle provides abstract access to the underlying keyset to 48 # limit the exposure of accessing the raw key material. WARNING: In practice, 49 # it is unlikely you will want to use a cleartext_keyset_handle, as it implies 50 # that your key material is passed in cleartext which is a security risk. 51 keyset_handle = cleartext_keyset_handle.read(tink.JsonKeysetReader(keyset)) 52 53 # Retrieve the DeterministicAead primitive we want to use from the keyset 54 # handle. 55 primitive = keyset_handle.primitive(daead.DeterministicAead) 56 57 # Use the primitive to encrypt a message. In this case the primary key of the 58 # keyset will be used (which is also the only key in this example). 59 ciphertext = primitive.encrypt_deterministically(b'msg', b'associated_data') 60 61 # Use the primitive to decrypt the message. Decrypt finds the correct key in 62 # the keyset and decrypts the ciphertext. If no key is found or decryption 63 # fails, it raises an error. 64 output = primitive.decrypt_deterministically(ciphertext, b'associated_data') 65 # [END deterministic-aead-basic-example] 66 assert output == b'msg' 67