xref: /aosp_15_r20/external/tink/python/examples/mac/mac_basic.py (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1# Copyright 2023 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 mac-basic-example]
16import tink
17from tink import cleartext_keyset_handle
18from tink import mac
19
20
21def example():
22  """Compute and verify MAC tags."""
23  # Register the MAC key managers. This is needed to create a Mac primitive
24  # later.
25  mac.register()
26
27  # Created with "tinkey create-keyset --key-template=HMAC_SHA256_128BITTAG".
28  # Note 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.HmacKey",
36              "value":
37                  "EgQIAxAQGiA0LQjovcydWhVQV3k8W9ZSRkd7Ei4Y/TRWApE8guwV4Q=="
38          },
39          "keyId": 1892702217,
40          "outputPrefixType": "TINK",
41          "status": "ENABLED"
42      }],
43      "primaryKeyId": 1892702217
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 Mac primitive we want to use from the keyset handle.
54  primitive = keyset_handle.primitive(mac.Mac)
55
56  # Use the primitive to compute the MAC for a message. In this case the primary
57  # key of the keyset will be used (which is also the only key in this example).
58  data = b'data'
59  tag = primitive.compute_mac(data)
60
61  # Use the primitive to verify the MAC for the message. Verify finds the
62  # correct key in the keyset and verifies the MAC. If no key is found or
63  # verification fails, it raises an error.
64  primitive.verify_mac(tag, data)
65  # [END mac-basic-example]
66