| 1 | // LAF Base Library |
|---|---|
| 2 | // Copyright (c) 2001-2016 David Capello |
| 3 | // |
| 4 | // This file is released under the terms of the MIT license. |
| 5 | // Read LICENSE.txt for more information. |
| 6 | |
| 7 | #ifdef HAVE_CONFIG_H |
| 8 | #include "config.h" |
| 9 | #endif |
| 10 | |
| 11 | #include "base/debug.h" |
| 12 | #include "base/fstream_path.h" |
| 13 | #include "base/sha1.h" |
| 14 | #include "base/sha1_rfc3174.h" |
| 15 | |
| 16 | #include <fstream> |
| 17 | |
| 18 | namespace base { |
| 19 | |
| 20 | Sha1::Sha1() |
| 21 | : m_digest(20, 0) |
| 22 | { |
| 23 | } |
| 24 | |
| 25 | Sha1::Sha1(const std::vector<uint8_t>& digest) |
| 26 | : m_digest(digest) |
| 27 | { |
| 28 | ASSERT(digest.size() == HashSize); |
| 29 | } |
| 30 | |
| 31 | // Calculates the SHA1 of the given file. |
| 32 | Sha1 Sha1::calculateFromFile(const std::string& fileName) |
| 33 | { |
| 34 | using namespace std; |
| 35 | |
| 36 | ifstream file(FSTREAM_PATH(fileName), ios::in | ios::binary); |
| 37 | if (!file.good()) |
| 38 | return Sha1(); |
| 39 | |
| 40 | SHA1Context sha; |
| 41 | SHA1Reset(&sha); |
| 42 | |
| 43 | unsigned char buf[1024]; |
| 44 | while (file.good()) { |
| 45 | file.read((char*)buf, 1024); |
| 46 | unsigned int len = (unsigned int)file.gcount(); |
| 47 | if (len > 0) |
| 48 | SHA1Input(&sha, buf, len); |
| 49 | } |
| 50 | |
| 51 | vector<uint8_t> digest(HashSize); |
| 52 | SHA1Result(&sha, &digest[0]); |
| 53 | |
| 54 | return Sha1(digest); |
| 55 | } |
| 56 | |
| 57 | // Calculates the SHA1 of the given string. |
| 58 | Sha1 Sha1::calculateFromString(const std::string& text) |
| 59 | { |
| 60 | SHA1Context sha; |
| 61 | SHA1Reset(&sha); |
| 62 | SHA1Input(&sha, (uint8_t*)text.c_str(), (unsigned int)text.size()); |
| 63 | |
| 64 | std::vector<uint8_t> digest(HashSize); |
| 65 | SHA1Result(&sha, &digest[0]); |
| 66 | |
| 67 | return Sha1(digest); |
| 68 | } |
| 69 | |
| 70 | bool Sha1::operator==(const Sha1& other) const |
| 71 | { |
| 72 | return m_digest == other.m_digest; |
| 73 | } |
| 74 | |
| 75 | bool Sha1::operator!=(const Sha1& other) const |
| 76 | { |
| 77 | return m_digest != other.m_digest; |
| 78 | } |
| 79 | |
| 80 | } // namespace base |
| 81 |