1 /*
2  * Copyright (c) 2023 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 #ifndef ANONYMOUS_UTILS_H
17 #define ANONYMOUS_UTILS_H
18 
19 #include <chrono>
20 #include <cstdio>
21 #include <stdlib.h>
22 #include <string>
23 
24 namespace OHOS {
25 namespace UpdateEngine {
26 static const int32_t ENCRYPT_LENGTH = 4; // 需要替换*的长度
27 static const int32_t ENCRYPT_TOTAL_LENGTH = 8; // 敏感数据匿名化后最长长度
28 static const std::string ENCRYPT_STR = "****";
29 
30 class AnonymousUtils {
31 public:
AnonymousUrl(const std::string & url)32     static std::string AnonymousUrl(const std::string &url)
33     {
34         std::string encryptUrl = url;
35         std::string httpsPrefix = "https://";
36         std::string httpPrefix = "http://";
37 
38         // 从https:// 或者 http:// 开始后面4位替换为 xxxx
39         if (encryptUrl.compare(0, httpsPrefix.size(), httpsPrefix) == 0) {
40             encryptUrl.replace(httpsPrefix.size(), ENCRYPT_LENGTH, ENCRYPT_STR);
41             return encryptUrl;
42         }
43         if (encryptUrl.compare(0, httpPrefix.size(), httpPrefix) == 0) {
44             encryptUrl.replace(httpPrefix.size(), ENCRYPT_LENGTH, ENCRYPT_STR);
45             return encryptUrl;
46         }
47         return encryptUrl;
48     }
49 
AnonymousString(std::string inputStr)50     static std::string AnonymousString(std::string inputStr)
51     {
52         if (inputStr.empty()) {
53             return inputStr;
54         }
55         std::string result;
56         size_t length = inputStr.length();
57         if (length >= ENCRYPT_TOTAL_LENGTH) {
58             std::string sequence = inputStr.substr(0, ENCRYPT_LENGTH);
59             result = sequence + ENCRYPT_STR;
60         } else if (length > ENCRYPT_LENGTH) {
61             std::string sequence = inputStr.substr(0, length - ENCRYPT_LENGTH);
62             result = sequence + ENCRYPT_STR;
63         } else {
64             result = ENCRYPT_STR;
65         }
66         return result;
67     }
68 };
69 } // namespace UpdateEngine
70 } // namespace OHOS
71 #endif // ANONYMOUS_UTILS_H