xref: /aosp_15_r20/external/tink/cc/examples/walkthrough/write_cleartext_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_cleartext_keyset.h"
18 
19 // [START tink_walkthrough_write_keyset]
20 #include <memory>
21 #include <ostream>
22 #include <utility>
23 
24 #include "absl/status/status.h"
25 #include "tink/cleartext_keyset_handle.h"
26 #include "tink/json_keyset_writer.h"
27 #include "tink/keyset_handle.h"
28 
29 namespace tink_walkthrough {
30 
31 using ::crypto::tink::JsonKeysetWriter;
32 using ::crypto::tink::util::StatusOr;
33 
34 // Writes a `keyset` to `output_stream` as a plaintext JSON format.
35 //
36 // Warning: Storing keys in cleartext is not recommended. We recommend using a
37 // Key Management Service to protect your keys. See
38 // https://github.com/google/tink/blob/master/cc/examples/walkthrough/write_keyset.cc
39 // for an example, and
40 // https://developers.google.com/tink/key-management-overview for more info on
41 // how to use a KMS with Tink.
42 //
43 // Prerequisites for this example:
44 //  - Create a keyset and obtain a KeysetHandle to it.
WriteKeyset(const crypto::tink::KeysetHandle & keyset,std::unique_ptr<std::ostream> output_stream)45 crypto::tink::util::Status WriteKeyset(
46     const crypto::tink::KeysetHandle& keyset,
47     std::unique_ptr<std::ostream> output_stream) {
48   StatusOr<std::unique_ptr<JsonKeysetWriter>> keyset_writer =
49       JsonKeysetWriter::New(std::move(output_stream));
50   if (!keyset_writer.ok()) return keyset_writer.status();
51   return crypto::tink::CleartextKeysetHandle::Write((keyset_writer)->get(),
52                                                     keyset);
53 }
54 
55 }  // namespace tink_walkthrough
56 // [END tink_walkthrough_write_keyset]
57