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
16 #include "hash_core.h"
17
18 #include <cstring>
19 #include <string_view>
20 #include <tuple>
21
22 #include "filemgmt_libhilog.h"
23 #include "hash_file.h"
24
25 namespace OHOS {
26 namespace FileManagement {
27 namespace ModuleFileIO {
28 using namespace std;
29
GetHashAlgorithm(const string & alg)30 static HASH_ALGORITHM_TYPE GetHashAlgorithm(const string &alg)
31 {
32 return (algorithmMaps.find(alg) != algorithmMaps.end()) ? algorithmMaps.at(alg) : HASH_ALGORITHM_TYPE_UNSUPPORTED;
33 }
34
DoHash(const string & path,const string & algorithm)35 FsResult<string> HashCore::DoHash(const string &path, const string &algorithm)
36 {
37 HASH_ALGORITHM_TYPE algType = GetHashAlgorithm(algorithm);
38 if (algType == HASH_ALGORITHM_TYPE_UNSUPPORTED) {
39 HILOGE("Invalid algoritm");
40 return FsResult<string>::Error(EINVAL);
41 }
42
43 int ret = EIO;
44 auto arg = make_shared<string>();
45 string &res = *arg;
46 if (algType == HASH_ALGORITHM_TYPE_MD5) {
47 tie(ret, res) = DistributedFS::HashFile::HashWithMD5(path);
48 } else if (algType == HASH_ALGORITHM_TYPE_SHA1) {
49 tie(ret, res) = DistributedFS::HashFile::HashWithSHA1(path);
50 } else if (algType == HASH_ALGORITHM_TYPE_SHA256) {
51 tie(ret, res) = DistributedFS::HashFile::HashWithSHA256(path);
52 }
53
54 if (ret) {
55 return FsResult<string>::Error(ret);
56 }
57
58 return FsResult<string>::Success(*arg);
59 }
60
61 } // namespace ModuleFileIO
62 } // namespace FileManagement
63 } // namespace OHOS