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/load_cleartext_keyset.h" 18 19 // [START tink_walkthrough_load_cleartext_keyset] 20 #include <iostream> 21 #include <memory> 22 #include <utility> 23 24 #include "absl/strings/string_view.h" 25 #include "tink/cleartext_keyset_handle.h" 26 #include "tink/json_keyset_reader.h" 27 #include "tink/keyset_handle.h" 28 #include "tink/keyset_reader.h" 29 #include "tink/util/statusor.h" 30 31 namespace tink_walkthrough { 32 33 using ::crypto::tink::util::StatusOr; 34 35 // Loads a JSON-serialized unencrypted keyset `serialized_keyset` and returns a 36 // KeysetHandle. 37 // 38 // Prerequisites for this example: 39 // - Create an plaintext keyset in JSON, for example, using Tinkey: 40 // 41 // tinkey create-key --key-template AES256_GCM \ 42 // --out-format json --out keyset.json 43 // LoadKeyset(absl::string_view serialized_keyset)44StatusOr<std::unique_ptr<crypto::tink::KeysetHandle>> LoadKeyset( 45 absl::string_view serialized_keyset) { 46 // To load a serialized keyset we need a JSON keyset reader. 47 StatusOr<std::unique_ptr<crypto::tink::KeysetReader>> reader = 48 crypto::tink::JsonKeysetReader::New(serialized_keyset); 49 if (!reader.ok()) return reader.status(); 50 // Parse and obtain the keyset using the reader. 51 return crypto::tink::CleartextKeysetHandle::Read(*std::move(reader)); 52 } 53 54 } // namespace tink_walkthrough 55 // [END tink_walkthrough_load_cleartext_keyset] 56