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 #include "udmf_utils.h"
16 #include <random>
17 #include <sstream>
18 #include "accesstoken_kit.h"
19 #include "ipc_skeleton.h"
20
21 namespace OHOS {
22 namespace UDMF {
23 namespace UTILS {
24 static constexpr int ID_LEN = 32;
25 static constexpr int MINIMUM = 48;
26 static constexpr int MAXIMUM = 121;
27 constexpr char SPECIAL = '^';
28
StrSplit(const std::string & str,const std::string & delimiter)29 std::vector<std::string> StrSplit(const std::string &str, const std::string &delimiter)
30 {
31 std::vector<std::string> result;
32 size_t start = 0;
33 size_t end = str.find(delimiter);
34 while (end != std::string::npos) {
35 result.push_back(str.substr(start, end - start));
36 start = end + delimiter.length();
37 end = str.find(delimiter, start);
38 }
39 result.push_back(str.substr(start));
40 return result;
41 }
42
Random(int32_t len,int32_t minimum,int32_t maximum)43 std::vector<uint8_t> Random(int32_t len, int32_t minimum, int32_t maximum)
44 {
45 std::random_device randomDevice;
46 std::uniform_int_distribution<int> distribution(minimum, maximum);
47 std::vector<uint8_t> key(len);
48 for (int32_t i = 0; i < len; i++) {
49 key[i] = static_cast<uint8_t>(distribution(randomDevice));
50 }
51 return key;
52 }
53
GenerateId()54 std::string GenerateId()
55 {
56 std::vector<uint8_t> randomDevices = Random(ID_LEN, MINIMUM, MAXIMUM);
57 std::stringstream idStr;
58 for (auto &randomDevice : randomDevices) {
59 auto asc = randomDevice;
60 asc = asc >= SPECIAL ? asc + 1 : asc;
61 idStr << static_cast<uint8_t>(asc);
62 }
63 return idStr.str();
64 }
65
GetSdkVersionByToken(uint32_t tokenId)66 std::string GetSdkVersionByToken(uint32_t tokenId)
67 {
68 if (Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) !=
69 Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
70 return "";
71 }
72 Security::AccessToken::HapTokenInfo hapTokenInfo;
73 auto ret = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapTokenInfo);
74 if (ret != 0) {
75 return "";
76 }
77 return std::to_string(hapTokenInfo.apiVersion);
78 }
79
GetCurrentSdkVersion()80 std::string GetCurrentSdkVersion()
81 {
82 return GetSdkVersionByToken(IPCSkeleton::GetSelfTokenID());
83 }
84 } // namespace UTILS
85 } // namespace UDMF
86 } // namespace OHOS