1 // Copyright 2018 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_writer.h"
18
19 #include <istream>
20 #include <memory>
21 #include <ostream>
22 #include <sstream>
23 #include <string>
24 #include <utility>
25
26 #include "absl/status/status.h"
27 #include "tink/util/errors.h"
28 #include "tink/util/protobuf_helper.h"
29 #include "tink/util/status.h"
30 #include "tink/util/statusor.h"
31 #include "proto/tink.pb.h"
32
33 using google::crypto::tink::EncryptedKeyset;
34 using google::crypto::tink::Keyset;
35
36
37 namespace crypto {
38 namespace tink {
39
40 namespace {
41
WriteProto(const portable_proto::MessageLite & proto,std::ostream * destination)42 util::Status WriteProto(const portable_proto::MessageLite& proto,
43 std::ostream* destination) {
44 std::string serialized_proto;
45 (*destination) << proto.SerializeAsString();
46 if (destination->fail()) {
47 return util::Status(absl::StatusCode::kUnknown,
48 "Error writing to the destination stream.");
49 }
50 return util::OkStatus();
51 }
52
53 } // anonymous namespace
54
55
56 // static
New(std::unique_ptr<std::ostream> destination_stream)57 util::StatusOr<std::unique_ptr<BinaryKeysetWriter>> BinaryKeysetWriter::New(
58 std::unique_ptr<std::ostream> destination_stream) {
59 if (destination_stream == nullptr) {
60 return util::Status(absl::StatusCode::kInvalidArgument,
61 "destination_stream must be non-null.");
62 }
63 std::unique_ptr<BinaryKeysetWriter> writer(
64 new BinaryKeysetWriter(std::move(destination_stream)));
65 return std::move(writer);
66 }
67
Write(const Keyset & keyset)68 util::Status BinaryKeysetWriter::Write(const Keyset& keyset) {
69 return WriteProto(keyset, destination_stream_.get());
70 }
71
Write(const EncryptedKeyset & encrypted_keyset)72 util::Status BinaryKeysetWriter::Write(
73 const EncryptedKeyset& encrypted_keyset) {
74 return WriteProto(encrypted_keyset, destination_stream_.get());
75 }
76
77 } // namespace tink
78 } // namespace crypto
79