xref: /aosp_15_r20/external/private-join-and-compute/private_join_and_compute/util/ec_key_util.cc (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 #include "private_join_and_compute/util/ec_key_util.h"
17 
18 #include "absl/strings/str_cat.h"
19 #include "private_join_and_compute/crypto/ec_group.h"
20 #include "private_join_and_compute/util/proto_util.h"
21 #include "private_join_and_compute/util/recordio.h"
22 
23 namespace private_join_and_compute::ec_key_util {
24 
GenerateEcKey(int curve_id,absl::string_view ec_key_filename)25 Status GenerateEcKey(int curve_id, absl::string_view ec_key_filename) {
26   Context context;
27   ASSIGN_OR_RETURN(ECGroup ec_group, ECGroup::Create(curve_id, &context));
28   BigNum key = ec_group.GeneratePrivateKey();
29   EcKeyProto key_proto;
30   key_proto.set_curve_id(curve_id);
31   key_proto.set_key(key.ToBytes());
32   return ProtoUtils::WriteProtoToFile(key_proto, ec_key_filename);
33 }
34 
DeserializeEcKey(Context * context,int curve_id,EcKeyProto ec_key_proto)35 StatusOr<BigNum> DeserializeEcKey(Context* context, int curve_id,
36                                   EcKeyProto ec_key_proto) {
37   if (curve_id != ec_key_proto.curve_id()) {
38     return InvalidArgumentError(absl::StrCat(
39         "EC key conversion failed, the given curve_id ", curve_id,
40         " doesn't match the proto curve id ", ec_key_proto.curve_id()));
41   }
42   return context->CreateBigNum(ec_key_proto.key());
43 }
44 
45 }  // namespace private_join_and_compute::ec_key_util
46