• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development 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 "crypto.h"
17 #include <iomanip>
18 #include <openssl/evp.h>
19 #include <sstream>
20 #include <vector>
21 #include "common/sharing_log.h"
22 
23 namespace OHOS {
24 namespace Sharing {
25 
GetMD5(const std::string & src)26 std::string GetMD5(const std::string &src)
27 {
28     int md5DigestLength = 4;
29     unsigned char MD5Hash[md5DigestLength];
30     std::string MD5Digest;
31     std::string tmp;
32     std::stringstream ss;
33 
34     for (int32_t i = 0; i < md5DigestLength; ++i) {
35         ss << std::hex << std::setw(2) << std::setfill('0') << (int32_t)MD5Hash[i] << std::endl; // 2: fix offset
36         ss >> tmp;
37         MD5Digest += tmp;
38     }
39 
40     return MD5Digest;
41 }
42 
GenerateSha256HashId(const uint8_t * originalId,uint32_t & len)43 std::vector<uint8_t> GenerateSha256HashId(const uint8_t *originalId, uint32_t &len)
44 {
45     if (originalId == nullptr || len == 0) {
46         return std::vector<uint8_t>{};
47     }
48 
49     std::unique_ptr<uint8_t[]> outHash = std::make_unique<uint8_t[]>(len);
50     uint32_t outLen = 0; // should be 32 bytes
51     int32_t ret = EVP_Digest(originalId, len, outHash.get(), &outLen, EVP_sha256(), nullptr);
52     if (ret != 1) {
53         SHARING_LOGE("Get Openssl Hash fail, %{public}d", ret);
54         return std::vector<uint8_t>{};
55     }
56     std::vector<uint8_t> result(outHash.get(), outHash.get() + outLen);
57     return result;
58 }
59 } // namespace Sharing
60 } // namespace OHOS