1 /*
2 * Copyright (C) 2024 The Android Open Source Project
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 "apex_sha.h"
18
19 #include <android-base/logging.h>
20 #include <openssl/sha.h>
21
22 #include <fstream>
23 #include <sstream>
24
25 static constexpr const int kBufSize = 1024;
26
27 using android::base::Error;
28 using android::base::Result;
29
30 namespace android {
31 namespace apex {
32
CalculateSha512(const std::string & path)33 Result<std::string> CalculateSha512(const std::string& path) {
34 LOG(DEBUG) << "Calculating SHA512 of " << path;
35 SHA512_CTX ctx;
36 SHA512_Init(&ctx);
37 std::ifstream apex(path, std::ios::binary);
38 if (apex.bad()) {
39 return Error() << "Failed to open " << path;
40 }
41 char buf[kBufSize];
42 while (!apex.eof()) {
43 apex.read(buf, kBufSize);
44 if (apex.bad()) {
45 return Error() << "Failed to read " << path;
46 }
47 int bytes_read = apex.gcount();
48 SHA512_Update(&ctx, buf, bytes_read);
49 }
50 uint8_t hash[SHA512_DIGEST_LENGTH];
51 SHA512_Final(hash, &ctx);
52 std::stringstream ss;
53 ss << std::hex;
54 for (int i = 0; i < SHA512_DIGEST_LENGTH; i++) {
55 ss << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
56 }
57 return ss.str();
58 }
59
CalculateSha256(const std::string & path)60 Result<std::string> CalculateSha256(const std::string& path) {
61 LOG(DEBUG) << "Calculating SHA256 of " << path;
62 SHA256_CTX ctx;
63 SHA256_Init(&ctx);
64 std::ifstream apex(path, std::ios::binary);
65 if (apex.bad()) {
66 return Error() << "Failed to open " << path;
67 }
68 char buf[kBufSize];
69 while (!apex.eof()) {
70 apex.read(buf, kBufSize);
71 if (apex.bad()) {
72 return Error() << "Failed to read " << path;
73 }
74 int bytes_read = apex.gcount();
75 SHA256_Update(&ctx, buf, bytes_read);
76 }
77 uint8_t hash[SHA256_DIGEST_LENGTH];
78 SHA256_Final(hash, &ctx);
79 std::stringstream ss;
80 ss << std::hex;
81 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
82 ss << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
83 }
84 return ss.str();
85 }
86
87 } // namespace apex
88 } // namespace android
89