AppInstallerSHA256.h (2938B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #pragma once 4 #include <filesystem> 5 #include <memory> 6 #include <string> 7 #include <vector> 8 #include <stdexcept> 9 #include <string_view> 10 11 namespace AppInstaller::Utility { 12 13 // Forward declaration of type defined within PAL 14 struct SHA256Context; 15 16 // Class used to compute SHA256 hashes over various sets of data. 17 // Create one and Add data to it if the data is not all available, 18 // or simply call ComputeHash if the data is all in memory. 19 class SHA256 20 { 21 public: 22 using HashBuffer = std::vector<uint8_t>; 23 constexpr static size_t HashBufferSizeInBytes = 32; 24 constexpr static size_t HashStringSizeInChars = 64; 25 26 struct HashDetails 27 { 28 HashBuffer Hash; 29 uint64_t SizeInBytes = 0; 30 }; 31 32 SHA256(); 33 34 // Adds the next chunk of data to the hash. 35 void Add(const uint8_t* buffer, size_t cbBuffer); 36 37 inline void Add(const std::vector<std::uint8_t>& buffer) 38 { 39 Add(buffer.data(), buffer.size()); 40 } 41 42 // Gets the hash of the data. This is a destructive action; the accumulated hash 43 // value will be returned and the object can no longer be used. 44 void Get(HashBuffer& hash); 45 46 inline HashBuffer Get() 47 { 48 HashBuffer result{}; 49 Get(result); 50 return result; 51 } 52 53 // Computes the hash of the given buffer immediately. 54 static HashBuffer ComputeHash(const uint8_t* buffer, std::uint32_t cbBuffer); 55 56 // Computes the hash of the given buffer immediately. 57 static HashBuffer ComputeHash(const std::vector<uint8_t>& buffer); 58 59 // Computes the hash of the given string immediately. 60 static HashBuffer ComputeHash(std::string_view buffer); 61 62 // Computes the hash from a given stream. 63 static HashBuffer ComputeHash(std::istream& in); 64 65 // Computes the hash from a given stream. 66 static HashDetails ComputeHashDetails(std::istream& in); 67 68 // Computes the hash from a given file path. 69 static HashBuffer ComputeHashFromFile(const std::filesystem::path& path); 70 71 static std::string ConvertToString(const HashBuffer& hashBuffer); 72 73 static std::wstring ConvertToWideString(const HashBuffer& hashBuffer); 74 75 static HashBuffer ConvertToBytes(const std::string& hashStr); 76 77 // Returns a value indicating whether the two hashes are equal. 78 static bool AreEqual(const HashBuffer& first, const HashBuffer& second); 79 80 private: 81 void EnsureNotFinished() const; 82 83 struct SHA256ContextDeleter 84 { 85 void operator()(SHA256Context* context); 86 }; 87 88 std::unique_ptr<SHA256Context, SHA256ContextDeleter> context; 89 }; 90 }