1 // Copyright 2017 Google Inc. 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 "tink/binary_keyset_reader.h" 18 19 #include <iostream> 20 #include <istream> 21 #include <memory> 22 #include <sstream> 23 #include <utility> 24 25 #include "absl/memory/memory.h" 26 #include "absl/status/status.h" 27 #include "tink/util/errors.h" 28 #include "tink/util/status.h" 29 #include "tink/util/statusor.h" 30 #include "proto/tink.pb.h" 31 32 namespace crypto { 33 namespace tink { 34 35 using google::crypto::tink::EncryptedKeyset; 36 using google::crypto::tink::Keyset; 37 38 // static New(std::unique_ptr<std::istream> keyset_stream)39util::StatusOr<std::unique_ptr<KeysetReader>> BinaryKeysetReader::New( 40 std::unique_ptr<std::istream> keyset_stream) { 41 if (keyset_stream == nullptr) { 42 return util::Status(absl::StatusCode::kInvalidArgument, 43 "keyset_stream must be non-null."); 44 } 45 std::stringstream buffer; 46 buffer << keyset_stream->rdbuf(); 47 return New(buffer.str()); 48 } 49 50 // static New(absl::string_view serialized_keyset)51util::StatusOr<std::unique_ptr<KeysetReader>> BinaryKeysetReader::New( 52 absl::string_view serialized_keyset) { 53 std::unique_ptr<KeysetReader> reader( 54 new BinaryKeysetReader(serialized_keyset)); 55 return std::move(reader); 56 } 57 Read()58util::StatusOr<std::unique_ptr<Keyset>> BinaryKeysetReader::Read() { 59 auto keyset = absl::make_unique<Keyset>(); 60 if (!keyset->ParseFromString(serialized_keyset_)) { 61 return util::Status(absl::StatusCode::kInvalidArgument, 62 "Could not parse the input stream as a Keyset-proto."); 63 } 64 return std::move(keyset); 65 } 66 67 util::StatusOr<std::unique_ptr<EncryptedKeyset>> ReadEncrypted()68BinaryKeysetReader::ReadEncrypted() { 69 auto enc_keyset = absl::make_unique<EncryptedKeyset>(); 70 if (!enc_keyset->ParseFromString(serialized_keyset_)) { 71 return util::Status( 72 absl::StatusCode::kInvalidArgument, 73 "Could not parse the input stream as an EncryptedKeyset-proto."); 74 } 75 return std::move(enc_keyset); 76 } 77 78 } // namespace tink 79 } // namespace crypto 80