1 // Copyright 2021 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 "tink/hybrid/internal/hpke_encrypt.h"
18
19 #include <memory>
20 #include <string>
21
22 #include "absl/status/status.h"
23 #include "tink/hybrid/internal/hpke_context.h"
24 #include "tink/hybrid/internal/hpke_util.h"
25 #include "proto/hpke.pb.h"
26
27 namespace crypto {
28 namespace tink {
29
30 using ::google::crypto::tink::HpkePublicKey;
31
New(const HpkePublicKey & recipient_public_key)32 util::StatusOr<std::unique_ptr<HybridEncrypt>> HpkeEncrypt::New(
33 const HpkePublicKey& recipient_public_key) {
34 if (recipient_public_key.public_key().empty()) {
35 return util::Status(absl::StatusCode::kInvalidArgument,
36 "Recipient public key is empty.");
37 }
38 if (!recipient_public_key.has_params()) {
39 return util::Status(absl::StatusCode::kInvalidArgument,
40 "Recipient public key is missing HPKE parameters.");
41 }
42 return {absl::WrapUnique(new HpkeEncrypt(recipient_public_key))};
43 }
44
Encrypt(absl::string_view plaintext,absl::string_view context_info) const45 util::StatusOr<std::string> HpkeEncrypt::Encrypt(
46 absl::string_view plaintext, absl::string_view context_info) const {
47 util::StatusOr<internal::HpkeParams> params =
48 internal::HpkeParamsProtoToStruct(recipient_public_key_.params());
49 if (!params.ok()) return params.status();
50
51 util::StatusOr<std::unique_ptr<internal::HpkeContext>> sender_context =
52 internal::HpkeContext::SetupSender(
53 *params, recipient_public_key_.public_key(), context_info);
54 if (!sender_context.ok()) return sender_context.status();
55
56 util::StatusOr<std::string> ciphertext =
57 (*sender_context)->Seal(plaintext, /*associated_data=*/"");
58 if (!ciphertext.ok()) return ciphertext.status();
59
60 return internal::ConcatenatePayload((*sender_context)->EncapsulatedKey(),
61 *ciphertext);
62 }
63
64 } // namespace tink
65 } // namespace crypto
66