xref: /aosp_15_r20/external/tink/cc/examples/walkthrough/write_keyset.cc (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 //
15 ///////////////////////////////////////////////////////////////////////////////
16 
17 #include "walkthrough/write_keyset.h"
18 
19 // [START tink_walkthrough_write_keyset]
20 #include <fstream>
21 #include <memory>
22 #include <ostream>
23 #include <utility>
24 
25 #include "absl/status/status.h"
26 #include "absl/strings/string_view.h"
27 #include "tink/aead.h"
28 #include "tink/json_keyset_writer.h"
29 #include "tink/keyset_handle.h"
30 #include "tink/kms_client.h"
31 #include "tink/kms_clients.h"
32 
33 namespace tink_walkthrough {
34 
35 using ::crypto::tink::JsonKeysetWriter;
36 using ::crypto::tink::util::StatusOr;
37 
38 // Writes a `keyset` to `output_stream` in JSON format; the keyset is encrypted
39 // through a KMS service using the KMS key `master_kms_key_uri`.
40 //
41 // Prerequisites for this example:
42 //  - Register AEAD implementations of Tink.
43 //  - Register a KMS client that can use `master_kms_key_uri`.
44 //  - Create a keyset and obtain a KeysetHandle to it.
WriteEncryptedKeyset(const crypto::tink::KeysetHandle & keyset,std::unique_ptr<std::ostream> output_stream,absl::string_view master_kms_key_uri)45 crypto::tink::util::Status WriteEncryptedKeyset(
46     const crypto::tink::KeysetHandle& keyset,
47     std::unique_ptr<std::ostream> output_stream,
48     absl::string_view master_kms_key_uri) {
49   // Create a writer that will write the keyset to output_stream as JSON.
50   StatusOr<std::unique_ptr<JsonKeysetWriter>> writer =
51       JsonKeysetWriter::New(std::move(output_stream));
52   if (!writer.ok()) return writer.status();
53   // Get a KMS client for the given key URI.
54   StatusOr<const crypto::tink::KmsClient*> kms_client =
55       crypto::tink::KmsClients::Get(master_kms_key_uri);
56   if (!kms_client.ok()) return kms_client.status();
57   // Get an Aead primitive that uses the KMS service to encrypt/decrypt.
58   StatusOr<std::unique_ptr<crypto::tink::Aead>> kms_aead =
59       (*kms_client)->GetAead(master_kms_key_uri);
60   if (!kms_aead.ok()) return kms_aead.status();
61   return keyset.Write(writer->get(), **kms_aead);
62 }
63 
64 }  // namespace tink_walkthrough
65 // [END tink_walkthrough_write_keyset]
66