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 <gmock/gmock.h>
19 #include <gtest/gtest.h>
20 
21 #include <filesystem>
22 #include <memory>
23 #include <string>
24 
25 #include "private_join_and_compute/crypto/context.h"
26 #include "private_join_and_compute/crypto/ec_group.h"
27 #include "private_join_and_compute/crypto/ec_key.pb.h"
28 #include "private_join_and_compute/crypto/openssl.inc"
29 #include "private_join_and_compute/util/proto_util.h"
30 #include "private_join_and_compute/util/status_testing.inc"
31 
32 namespace private_join_and_compute::ec_key_util {
33 namespace {
34 using ::testing::Test;
35 
36 const int kTestCurveId = NID_X9_62_prime256v1;
37 
TEST(EcKeyUtilTest,GenerateKey)38 TEST(EcKeyUtilTest, GenerateKey) {
39   std::filesystem::path temp_dir(::testing::TempDir());
40   std::string key_filename = (temp_dir / "ec.key").string();
41 
42   // Generate an EC key.
43   ASSERT_OK(GenerateEcKey(kTestCurveId, key_filename));
44   ASSERT_TRUE(std::filesystem::exists(key_filename));
45 
46   // Read the key and verify it is valid.
47   Context context;
48   ASSERT_OK_AND_ASSIGN(auto ec_group, ECGroup::Create(kTestCurveId, &context));
49   ASSERT_OK_AND_ASSIGN(auto key_proto,
50                        ProtoUtils::ReadProtoFromFile<EcKeyProto>(key_filename));
51   ASSERT_OK_AND_ASSIGN(auto key,
52                        DeserializeEcKey(&context, kTestCurveId, key_proto));
53   EXPECT_OK(ec_group.CheckPrivateKey(key));
54 }
55 }  // namespace
56 }  // namespace private_join_and_compute::ec_key_util
57