xref: /aosp_15_r20/external/tink/python/examples/walkthrough/write_keyset_test.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"""Test for write_keyset."""
15import io
16
17from absl.testing import absltest
18import tink
19from tink import aead
20
21import create_keyset
22import load_encrypted_keyset
23import write_keyset
24
25from tink.testing import fake_kms
26
27# Fake KMS keys are base64-encoded keysets. This was generated from
28# an AEAD keyser by first serializing it to bytes using a
29# tink.BinaryKeysetWriter, and then encoding it as base64.
30_FAKE_KMS_KEY_URI = (
31    'fake-kms://COiSsYwBEmQKWAowdHlwZS5nb29nbGVhcGlzLmNvbS9nb29nbGUuY3J5cHRvLnR'
32    'pbmsuQWVzR2NtS2V5EiIaIFbJR8aBiTdFNGGP8shTNK50haXKMJ-0I7KlOvSMI1IuGAEQARjok'
33    'rGMASAB')
34
35
36class CreateKeysetTest(absltest.TestCase):
37
38  def setUp(self):
39    super().setUp()
40    aead.register()
41    fake_kms.register_client()
42
43  def test_write_keyset_fails_if_kms_key_is_invalid(self):
44    keyset_handle = create_keyset.CreateAead128GcmKeyset()
45    text_io = io.StringIO()
46    with self.assertRaises(tink.TinkError):
47      write_keyset.WriteEncryptedKeyset(
48          keyset_handle,
49          text_io,
50          kms_kek_uri='fake-kms://invalid-kms-key',
51          associated_data=b'')
52
53  def test_write_keyset_serializes_a_keyset_correctly(self):
54    associated_data = b'some associated data'
55    keyset_handle = create_keyset.CreateAead128GcmKeyset()
56    text_io = io.StringIO()
57    write_keyset.WriteEncryptedKeyset(keyset_handle, text_io, _FAKE_KMS_KEY_URI,
58                                      associated_data)
59
60    # Make sure that we can use this primitive.
61    aead_primitive = keyset_handle.primitive(aead.Aead)
62
63    loaded_keyset_handle = load_encrypted_keyset.LoadEncryptedKeyset(
64        text_io.getvalue(), _FAKE_KMS_KEY_URI, associated_data)
65    loaded_aead = loaded_keyset_handle.primitive(aead.Aead)
66    plaintext = b'some plaintext'
67
68    self.assertEqual(
69        loaded_aead.decrypt(
70            aead_primitive.encrypt(plaintext, associated_data),
71            associated_data), plaintext)
72    self.assertEqual(
73        aead_primitive.decrypt(
74            loaded_aead.encrypt(plaintext, associated_data), associated_data),
75        plaintext)
76
77
78if __name__ == '__main__':
79  absltest.main()
80