• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2021-2022 Huawei Technologies Co., Ltd
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "utils/system/sha256.h"
18 #include <sys/stat.h>
19 #include <iomanip>
20 #include <fstream>
21 #include <vector>
22 #include <algorithm>
23 #include <numeric>
24 #include "securec/include/securec.h"
25 #include "utils/log_adapter.h"
26 #include "utils/convert_utils_base.h"
27 #include "utils/os.h"
28 
29 namespace mindspore {
30 namespace system {
31 namespace sha256 {
32 constexpr int kBitNumber = 8;
33 constexpr int kDigestSize = 8;
34 constexpr int kIterationNumber = 64;
35 constexpr int kMessageBlockLength = 64;
36 const uint32_t constant[64] = {
37   0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
38   0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
39   0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
40   0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
41   0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
42   0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
43   0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
44   0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
45 
LoadFilePath(const std::string & path)46 std::string LoadFilePath(const std::string &path) {
47   char real_path[PATH_MAX] = {0};
48 #if defined(_WIN32) || defined(_WIN64)
49   if (path.size() >= PATH_MAX || _fullpath(real_path, path.c_str(), PATH_MAX) == nullptr) {
50     return "";
51   }
52 #else
53   if (path.size() >= PATH_MAX || realpath(path.c_str(), real_path) == nullptr) {
54     return "";
55   }
56 #endif
57   std::ifstream bin_stream(real_path, std::ios::binary);
58   if (!bin_stream.is_open()) {
59     return "";
60   }
61   std::string message((std::istreambuf_iterator<char>(bin_stream)), std::istreambuf_iterator<char>());
62   return message;
63 }
64 
Padding(std::string * message)65 bool Padding(std::string *message) {
66   uint64_t bits_message = message->size() * kBitNumber;
67   const int remains = message->size() % kMessageBlockLength;
68   // The length of the message needs to be stored in 8 bytes, supplemented at the end of the message.
69   const int size_append = 8;
70   const int size_required = kMessageBlockLength - size_append;
71   const int size_pad = size_required - remains + (size_required > remains ? 0 : kMessageBlockLength);
72   if (size_pad < 1 || size_pad > kMessageBlockLength) {
73     return false;
74   }
75   message->push_back(0x80);
76   for (int i = 1; i < size_pad; ++i) {
77     message->push_back(0x00);
78   }
79   for (int i = size_append - 1; i >= 0; --i) {
80     message->push_back(static_cast<char>((bits_message >> static_cast<uint32_t>(i * kBitNumber)) & 0xff));
81   }
82   return true;
83 }
84 
ProcessInner(const std::string & message,const int & bias,uint32_t * digest,const int & digest_size)85 bool ProcessInner(const std::string &message, const int &bias, uint32_t *digest, const int &digest_size) {
86   if (digest_size != 8) {  // The number of digests is fixed at 8
87     return false;
88   }
89   uint32_t w[kIterationNumber] = {0};
90   for (int i = 0; i < 16; ++i) {
91     w[i] = (static_cast<uint32_t>(static_cast<uint8_t>(message[IntToSize(bias + i * 4)]) & 0xff) << 24) |
92            (static_cast<uint32_t>(static_cast<uint8_t>(message[IntToSize(bias + i * 4 + 1)]) & 0xff) << 16) |
93            (static_cast<uint32_t>(static_cast<uint8_t>(message[IntToSize(bias + i * 4 + 2)]) & 0xff) << 8) |
94            (static_cast<uint32_t>(static_cast<uint8_t>(message[IntToSize(bias + i * 4 + 3)]) & 0xff));
95   }
96   for (int i = 16; i < kIterationNumber; ++i) {
97     w[i] = sigma3(w[i - 2]) + w[i - 7] + sigma2(w[i - 15]) + w[i - 16];
98   }
99 
100   std::vector<uint32_t> hash(digest_size);
101   size_t mem_size = IntToSize(digest_size) * sizeof(uint32_t);
102   errno_t ret = memcpy_s(hash.data(), mem_size, digest, mem_size);
103   if (ret != EOK) {
104     return false;
105   }
106   for (int i = 0; i < kIterationNumber; ++i) {
107     uint32_t t1 = w[i] + constant[i] + hash[7] + sigma1(hash[4]) + ch(hash[4], hash[5], hash[6]);
108     uint32_t t2 = sigma0(hash[0]) + ma(hash[0], hash[1], hash[2]);
109     for (int j = digest_size - 1; j >= 0; --j) {
110       if (j == 4) {
111         hash[IntToSize(j)] = hash[IntToSize(j - 1)] + t1;
112       } else if (j == 0) {
113         hash[IntToSize(j)] = t1 + t2;
114       } else {
115         hash[IntToSize(j)] = hash[IntToSize(j - 1)];
116       }
117     }
118   }
119   for (size_t i = 0; i < IntToSize(digest_size); ++i) {
120     digest[i] += hash[i];
121   }
122   return true;
123 }
124 
ConvertToString(const uint32_t * input,const int & size)125 std::string ConvertToString(const uint32_t *input, const int &size) {
126   std::ostringstream oss;
127   oss << std::hex;
128   for (int i = 0; i < size; ++i) {
129     for (int j = static_cast<int>(sizeof(uint32_t) / sizeof(uint8_t)) - 1; j >= 0; --j) {
130       auto val = static_cast<uint8_t>((input[i] >> static_cast<uint32_t>(j * kBitNumber)) & 0xff);
131       oss << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(val);
132     }
133   }
134   return oss.str();
135 }
136 
Encrypt(const std::string & message)137 std::string Encrypt(const std::string &message) {
138   uint32_t digest[kDigestSize] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
139                                   0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
140   for (int i = 0; i < static_cast<int>(message.size()); i += kMessageBlockLength) {
141     if (!ProcessInner(message, i, digest, kDigestSize)) {
142       return "";
143     }
144   }
145   return ConvertToString(digest, kDigestSize);
146 }
147 
GetHashFromString(const std::string & data)148 std::string GetHashFromString(const std::string &data) {
149   std::string message = data;
150   if (message.empty() || !Padding(&message)) {
151     return "";
152   }
153   return Encrypt(message);
154 }
155 
GetHashFromFile(const std::string & path)156 std::string GetHashFromFile(const std::string &path) {
157   std::string message = LoadFilePath(path);
158   if (message.empty() || !Padding(&message)) {
159     return "";
160   }
161   return Encrypt(message);
162 }
163 
164 #ifndef _WIN32
GetHashFromDir(const std::string & dir)165 std::string GetHashFromDir(const std::string &dir) {
166   if (dir.empty()) {
167     MS_LOG(ERROR) << "The directory path is empty.";
168     return "";
169   }
170   struct stat s {};
171   int ret = stat(dir.c_str(), &s);
172   if (ret != 0) {
173     MS_LOG(ERROR) << "stat dir \"" << dir << "\" failed, ret is : " << ret;
174     return "";
175   }
176   if (!S_ISDIR(s.st_mode)) {
177     MS_LOG(ERROR) << "The path \"" << dir << "\" is not a directory.";
178     return "";
179   }
180   DIR *open_dir = opendir(dir.c_str());
181   if (open_dir == nullptr) {
182     MS_LOG(ERROR) << "open dir " << dir.c_str() << " failed";
183     return "";
184   }
185   struct dirent *filename;
186   std::vector<std::string> file_hashes;
187   while ((filename = readdir(open_dir)) != nullptr) {
188     std::string d_name = std::string(filename->d_name);
189     if (d_name == "." || d_name == ".." || filename->d_type != DT_REG) {
190       continue;
191     }
192     (void)file_hashes.emplace_back(GetHashFromFile(std::string(dir) + "/" + filename->d_name));
193   }
194   (void)closedir(open_dir);
195   std::sort(file_hashes.begin(), file_hashes.end());
196   auto dir_hash = std::accumulate(file_hashes.begin(), file_hashes.end(), std::string{});
197   return dir_hash;
198 }
199 #endif
200 }  // namespace sha256
201 }  // namespace system
202 }  // namespace mindspore
203