1 /* 2 * Copyright (C) 2025 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 #ifndef HAP_UTIL_STRING_HASH_H 16 #define HAP_UTIL_STRING_HASH_H 17 18 #include <iostream> 19 #include <string> 20 #include <iomanip> 21 #include <sstream> 22 #include <openssl/sha.h> 23 24 namespace OHOS { 25 namespace Security { 26 namespace Verify { 27 // for separator 28 constexpr char UUID_SEPARATOR = '-'; 29 const std::vector<int32_t> SEPARATOR_POSITIONS { 8, 13, 18, 23}; 30 const size_t UUID_ORIGIN_SIZE = 32; 31 const uint8_t BIT_TWO = 2; 32 class StringHash { 33 public: 34 // Generate SHA-256 hash of the input string GenerateUuidByKey(const std::string & input)35 static std::string GenerateUuidByKey(const std::string &input) 36 { 37 // SHA256 produces 32-byte hash 38 unsigned char hash[SHA256_DIGEST_LENGTH]; 39 40 // Compute SHA256 41 SHA256_CTX sha256; 42 SHA256_Init(&sha256); // Initialize context 43 SHA256_Update(&sha256, input.c_str(), input.size()); // Feed data to hash 44 SHA256_Final(hash, &sha256); // Get final hash 45 46 // Convert binary hash to hexadecimal string 47 std::stringstream ss; 48 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { 49 ss << std::hex << std::setw(BIT_TWO) << std::setfill('0') << (int)hash[i]; 50 } 51 std::string hashString = ss.str(); 52 // Format the hash string to match UUID format 53 hashString = hashString.substr(0, UUID_ORIGIN_SIZE); 54 for (int32_t index : SEPARATOR_POSITIONS) { 55 hashString.insert(index, 1, UUID_SEPARATOR); 56 } 57 58 return hashString; 59 } 60 }; 61 } // namespace Verify 62 } // namespace Security 63 } // namespace OHOS 64 #endif // HAP_UTIL_STRING_HASH_H 65