xref: /aosp_15_r20/external/private-join-and-compute/private_join_and_compute/crypto/ec_point_util.h (revision a6aa18fbfbf9cb5cd47356a9d1b057768998488c)
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 #ifndef PRIVATE_JOIN_AND_COMPUTE_EC_POINT_UTIL_H_
17 #define PRIVATE_JOIN_AND_COMPUTE_EC_POINT_UTIL_H_
18 
19 #include <memory>
20 #include <string>
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 
32 // ECPointUtil class to allow generating random EC points, hashing to the
33 // elliptic curve, and checking if strings encode curve points.
34 
35 class ECPointUtil {
36  public:
37   // ECPointUtil is neither copyable nor assignable.
38   ECPointUtil(const ECPointUtil&) = delete;
39   ECPointUtil& operator=(const ECPointUtil&) = delete;
40 
41   // Creates an ECPointUtil object.
42   // Returns INVALID_ARGUMENT status instead if the curve_id is not valid
43   // or INTERNAL status when crypto operations are not successful.
44   static StatusOr<std::unique_ptr<ECPointUtil>> Create(int curve_id);
45 
46   // Returns a random EC point on the curve
47   StatusOr<std::string> GetRandomCurvePoint();
48 
49   // Hashes the given string to the curve.
50   //
51   // Suggested default hash_type is ECCommutativeCipher::HashType::Sha256.
52   StatusOr<std::string> HashToCurve(absl::string_view input,
53                                     ECCommutativeCipher::HashType hash_type);
54 
55   // Checks if a string represents a curve point.
56   // May give a false negative if an internal error occurs.
57   bool IsCurvePoint(absl::string_view input);
58 
59  private:
60   ECPointUtil(std::unique_ptr<Context> context, ECGroup group);
61 
62   // Context used for storing temporary values to be reused across openssl
63   // function calls for better performance.
64   std::unique_ptr<Context> context_;
65 
66   // The EC Group representing the curve definition.
67   ECGroup group_;
68 };
69 
70 }  // namespace private_join_and_compute
71 
72 #endif  // PRIVATE_JOIN_AND_COMPUTE_EC_POINT_UTIL_H_
73