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