xref: /aosp_15_r20/external/tink/python/examples/walkthrough/load_encrypted_keyset.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"""Example to showcase how to load an encrypted keyset."""
15# [START tink_walkthrough_load_encrypted_keyset]
16import tink
17
18from tink import aead
19
20
21def LoadEncryptedKeyset(json_serialized_encrypted_keyset: str, kms_key_uri: str,
22                        associated_data: bytes) -> tink.KeysetHandle:
23  r"""Loads a JSON-serialized keyset that was encrypted with a KMS.
24
25  Prerequisites for this example:
26  - Register AEAD implementations of Tink.
27  - Register a KMS client for the given URI prefix. Tink Python provides
28    awskms.AwsKmsClient.register_client() and
29    gcpkms.GcpKmsClient.register_client() for AWS-KMS and Google Cloud KMS
30    respectively.
31  - Create a KMS encrypted keyset, for example using Tinkey with Google Cloud
32    KMS:
33
34    tinkey create-keyset --key-template AES128_GCM \
35      --out-format json --out encrypted_aead_keyset.json \
36      --master-key-uri gcp-kms://<KMS key uri> \
37      --credentials gcp_credentials.json
38
39  Args:
40    json_serialized_encrypted_keyset: JSON serialized keyset.
41    kms_key_uri: The URI of the KMS key to use to decrypt the keyset.
42    associated_data: Associated data.
43
44  Returns:
45    A handle to the loaded keyset.
46
47  Raises:
48    tink.TinkError in case of errors.
49  """
50  # To obtain a primitive that uses the KMS to encrypt/decrypt we simply create
51  # keyset from the appropriate template and get an AEAD primitive from it.
52  template = aead.aead_key_templates.create_kms_aead_key_template(kms_key_uri)
53  keyset_handle = tink.new_keyset_handle(template)
54  kms_aead = keyset_handle.primitive(aead.Aead)
55  return tink.read_keyset_handle_with_associated_data(
56      tink.JsonKeysetReader(json_serialized_encrypted_keyset), kms_aead,
57      associated_data)
58
59
60# [END tink_walkthrough_load_encrypted_keyset]
61