1 /*
2  * Copyright (c) 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 "mock_utils.h"
17 #include "dlp_permission_log.h"
18 #include "hex_string.h"
19 #include "nlohmann/json.hpp"
20 #include "securec.h"
21 
22 namespace {
23 static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_DLP_PERMISSION, "MockUtil" };
24 static const std::string POLICY_CERT = "policyCert";
25 static const std::string TEXT_CERT = "plaintextPolicy";
26 }
27 using unordered_json = nlohmann::ordered_json;
28 
ModifyParseData(uint8_t ** data,uint32_t * dataLen,uint8_t * dataIn,uint32_t dataInLen)29 bool ModifyParseData(uint8_t** data, uint32_t* dataLen, uint8_t* dataIn, uint32_t dataInLen)
30 {
31     uint32_t encDataHexLen = dataInLen * OHOS::Security::DlpPermission::BYTE_TO_HEX_OPER_LENGTH + 1;
32     char* encDataHex = new (std::nothrow) char[encDataHexLen];
33     if (encDataHex == nullptr) {
34         DLP_LOG_ERROR(LABEL, "New memory fail.");
35         return false;
36     }
37     int32_t res = OHOS::Security::DlpPermission::ByteToHexString(dataIn, dataInLen, encDataHex, encDataHexLen);
38     if (res != 0) {
39         memset_s(encDataHex, encDataHexLen, 0, encDataHexLen);
40         delete[] encDataHex;
41         return false;
42     }
43     std::string txtStr = encDataHex;
44     unordered_json json;
45     json[TEXT_CERT] = txtStr;
46     json[POLICY_CERT] = unordered_json::parse(dataIn, dataIn + dataInLen + 1, nullptr, false);
47     std::string certStr = json.dump();
48     *data = reinterpret_cast<uint8_t *>(strdup(const_cast<char *>(certStr.c_str())));
49     *dataLen = certStr.length();
50     memset_s(encDataHex, encDataHexLen, 0, encDataHexLen);
51     delete[] encDataHex;
52     return true;
53 }