1 /*
2 * Copyright 2019 Google LLC.
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 * https://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 #include "private_join_and_compute/crypto/ec_point_util.h"
17
18 #include <memory>
19 #include <string>
20 #include <utility>
21
22 #include "absl/strings/string_view.h"
23 #include "private_join_and_compute/crypto/big_num.h"
24 #include "private_join_and_compute/crypto/context.h"
25 #include "private_join_and_compute/crypto/ec_commutative_cipher.h"
26 #include "private_join_and_compute/crypto/ec_group.h"
27 #include "private_join_and_compute/crypto/ec_point.h"
28 #include "private_join_and_compute/util/status.inc"
29
30 namespace private_join_and_compute {
31
ECPointUtil(std::unique_ptr<Context> context,ECGroup group)32 ECPointUtil::ECPointUtil(std::unique_ptr<Context> context, ECGroup group)
33 : context_(std::move(context)), group_(std::move(group)) {}
34
Create(int curve_id)35 StatusOr<std::unique_ptr<ECPointUtil>> ECPointUtil::Create(int curve_id) {
36 std::unique_ptr<Context> context(new Context());
37 ASSIGN_OR_RETURN(ECGroup group, ECGroup::Create(curve_id, context.get()));
38 return std::unique_ptr<ECPointUtil>(
39 new ECPointUtil(std::move(context), std::move(group)));
40 }
41
GetRandomCurvePoint()42 StatusOr<std::string> ECPointUtil::GetRandomCurvePoint() {
43 ASSIGN_OR_RETURN(ECPoint point, group_.GetRandomGenerator());
44 return point.ToBytesCompressed();
45 }
46
HashToCurve(absl::string_view input,ECCommutativeCipher::HashType hash_type)47 StatusOr<std::string> ECPointUtil::HashToCurve(
48 absl::string_view input, ECCommutativeCipher::HashType hash_type) {
49 if (hash_type == ECCommutativeCipher::HashType::SHA512) {
50 ASSIGN_OR_RETURN(ECPoint point,
51 group_.GetPointByHashingToCurveSha512(input));
52 return point.ToBytesCompressed();
53 }
54
55 if (hash_type == ECCommutativeCipher::HashType::SHA256) {
56 ASSIGN_OR_RETURN(ECPoint point,
57 group_.GetPointByHashingToCurveSha256(input));
58 return point.ToBytesCompressed();
59 }
60
61 return InvalidArgumentError("Invalid hash type.");
62 }
63
IsCurvePoint(absl::string_view input)64 bool ECPointUtil::IsCurvePoint(absl::string_view input) {
65 return group_.CreateECPoint(input).ok();
66 }
67
68 } // namespace private_join_and_compute
69