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 ENCRYPT_UTILS_H 17 #define ENCRYPT_UTILS_H 18 19 #include <chrono> 20 #include <cstdio> 21 #include <stdlib.h> 22 #include <string> 23 24 #include "update_log.h" 25 namespace OHOS { 26 namespace UpdateEngine { 27 static const int32_t ENCRYPT_LENGTH = 4; // 需要替换*的长度 28 static const int32_t ENCRYPT_TOTAL_LENGTH = 8; // 敏感数据匿名化后最长长度 29 static const std::string ENCRYPT_STR = "****"; 30 31 class EncryptUtils { 32 public: GetRand(int32_t min,int32_t max)33 static int64_t GetRand(int32_t min, int32_t max) 34 { 35 // 随机 min ~ max值 36 if (max < min) { 37 return min; 38 } 39 srand(time(nullptr)); 40 return min + rand() % (max - min); 41 } 42 EncryptUrl(const std::string & url)43 static std::string EncryptUrl(const std::string &url) 44 { 45 std::string encryptUrl = url; 46 std::string httpsPrefix = "https://"; 47 std::string httpPrefix = "http://"; 48 49 // 从https:// 或者 http:// 开始后面4位替换为 xxxx 50 if (encryptUrl.compare(0, httpsPrefix.size(), httpsPrefix) == 0) { 51 encryptUrl.replace(httpsPrefix.size(), ENCRYPT_LENGTH, ENCRYPT_STR); 52 return encryptUrl; 53 } 54 if (encryptUrl.compare(0, httpPrefix.size(), httpPrefix) == 0) { 55 encryptUrl.replace(httpPrefix.size(), ENCRYPT_LENGTH, ENCRYPT_STR); 56 return encryptUrl; 57 } 58 return encryptUrl; 59 } 60 EncryptString(std::string inputStr)61 static std::string EncryptString(std::string inputStr) 62 { 63 if (inputStr.empty()) { 64 return inputStr; 65 } 66 std::string result; 67 size_t length = inputStr.length(); 68 if (length >= ENCRYPT_TOTAL_LENGTH) { 69 std::string sequence = inputStr.substr(0, ENCRYPT_LENGTH); 70 result = sequence + ENCRYPT_STR; 71 } else if (length > ENCRYPT_LENGTH) { 72 std::string sequence = inputStr.substr(0, length - ENCRYPT_LENGTH); 73 result = sequence + ENCRYPT_STR; 74 } else { 75 result = ENCRYPT_STR; 76 } 77 return result; 78 } 79 }; 80 } // namespace UpdateEngine 81 } // namespace OHOS 82 #endif // ENCRYPT_UTILS_H