xref: /aosp_15_r20/external/tink/python/examples/aead/aead_basic.py (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
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 AEAD API."""
15 # [START aead-basic-example]
16 import tink
17 from tink import aead
18 from tink import cleartext_keyset_handle
19 
20 
21 def example():
22   """Encrypt and decrypt using AEAD."""
23   # Register the AEAD key managers. This is needed to create an Aead primitive
24   # later.
25   aead.register()
26 
27   # A keyset created with "tinkey create-keyset --key-template=AES256_GCM". 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.AesGcmKey",
36               "value":
37                   "GiBWyUfGgYk3RTRhj/LIUzSudIWlyjCftCOypTr0jCNSLg=="
38           },
39           "keyId": 294406504,
40           "outputPrefixType": "TINK",
41           "status": "ENABLED"
42       }],
43       "primaryKeyId": 294406504
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 access of the raw key material. WARNING: In practice, it is unlikely
49   # you will want to use a cleartext_keyset_handle, as it implies that your key
50   # material is passed in cleartext, which is a security risk.
51   keyset_handle = cleartext_keyset_handle.read(tink.JsonKeysetReader(keyset))
52 
53   # Retrieve the Aead primitive we want to use from the keyset handle.
54   primitive = keyset_handle.primitive(aead.Aead)
55 
56   # Use the primitive to encrypt a message. In this case the primary key of the
57   # keyset will be used (which is also the only key in this example).
58   ciphertext = primitive.encrypt(b'msg', b'associated_data')
59 
60   # Use the primitive to decrypt the message. Decrypt finds the correct key in
61   # the keyset and decrypts the ciphertext. If no key is found or decryption
62   # fails, it raises an error.
63   output = primitive.decrypt(ciphertext, b'associated_data')
64   # [END aead-basic-example]
65   assert output == b'msg'
66