1 /*
2  * Copyright (C) 2023-2024 Huawei Device Co., Ltd.
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 #include "dhkeyutil_fuzzer.h"
17 
18 #include <cstddef>
19 #include <cstdint>
20 #include <string>
21 #include "securec.h"
22 
23 #include "dh_key_util.h"
24 #include "blob.h"
25 #include "detailed_dh_key_params.h"
26 #include "result.h"
27 
28 using namespace std;
29 
30 namespace OHOS {
31     static bool g_testFlag = true;
32     constexpr int32_t HCF_DH_PLEN_2048 = 2048;
TestDhKey(void)33     static void TestDhKey(void)
34     {
35         HcfDhCommParamsSpec *returnCommonParamSpec = nullptr;
36         int32_t res = HcfDhKeyUtilCreate(3072, 512, &returnCommonParamSpec);
37         if (res != HCF_SUCCESS) {
38             return;
39         }
40         FreeDhCommParamsSpec(returnCommonParamSpec);
41     }
42 
DhKeyUtilFuzzTest(const uint8_t * data,size_t size)43     bool DhKeyUtilFuzzTest(const uint8_t* data, size_t size)
44     {
45         if (size < (sizeof(int32_t) / sizeof(uint8_t))) {
46             return false;
47         }
48         if (g_testFlag) {
49             TestDhKey();
50             g_testFlag = false;
51         }
52         HcfDhCommParamsSpec *returnCommonParamSpec = nullptr;
53         int32_t skLen = 0;
54         const int32_t int32Size = sizeof(int32_t);
55         (void)memcpy_s(&skLen, int32Size, data, int32Size);
56         HcfResult res = HcfDhKeyUtilCreate(HCF_DH_PLEN_2048, skLen, &returnCommonParamSpec);
57         if (res != HCF_SUCCESS) {
58             return false;
59         }
60         FreeDhCommParamsSpec(returnCommonParamSpec);
61         return true;
62     }
63 }
64 
65 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)66 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
67 {
68     /* Run your code on data */
69     OHOS::DhKeyUtilFuzzTest(data, size);
70     return 0;
71 }
72