xref: /aosp_15_r20/external/tink/python/examples/walkthrough/write_cleartext_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_cleartext_keyset."""
15import io
16
17from absl.testing import absltest
18
19from tink import aead
20
21import create_keyset
22import load_cleartext_keyset
23import write_cleartext_keyset
24
25
26class LoadCleartextKeysetTest(absltest.TestCase):
27
28  def test_write_cleartext_keyset_serializes_a_keyset_correctly(self):
29    aead.register()
30    keyset_handle = create_keyset.CreateAead128GcmKeyset()
31    string_io = io.StringIO()
32    write_cleartext_keyset.WriteKeyset(keyset_handle, string_io)
33
34    # Make sure that we can deserialize the keyset and use the contained
35    # primitive.
36    deserialized_keyset_handle = load_cleartext_keyset.LoadKeyset(
37        string_io.getvalue())
38    deserialized_aead_primitive = deserialized_keyset_handle.primitive(
39        aead.Aead)
40    aead_primitive = keyset_handle.primitive(aead.Aead)
41
42    plaintext = b'Some plaintext'
43    associated_data = b'Some associated data'
44
45    self.assertEqual(
46        deserialized_aead_primitive.decrypt(
47            aead_primitive.encrypt(plaintext, associated_data),
48            associated_data), plaintext)
49
50    self.assertEqual(
51        aead_primitive.decrypt(
52            deserialized_aead_primitive.encrypt(plaintext, associated_data),
53            associated_data), plaintext)
54
55
56if __name__ == '__main__':
57  absltest.main()
58