Welcome to mirror list, hosted at ThFree Co, Russian Federation.

sha1.cpp « coding - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b1c412eed0bc68b9553dcf5b0bb6ce95ce1f518a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "coding/sha1.hpp"

#include "coding/internal/file_data.hpp"
#include "coding/file_reader.hpp"

#include "base/assert.hpp"
#include "base/logging.hpp"
#include "base/macros.hpp"

#include "3party/liboauthcpp/src/SHA1.h"
#include "3party/liboauthcpp/src/base64.h"

#include <algorithm>
#include <vector>

namespace coding
{
// static
SHA1::Hash SHA1::Calculate(std::string const & filePath)
{
  uint32_t constexpr kFileBufferSize = 8192;
  try
  {
    base::FileData file(filePath, base::FileData::OP_READ);
    uint64_t const fileSize = file.Size();

    CSHA1 sha1;
    uint64_t currSize = 0;
    unsigned char buffer[kFileBufferSize];
    while (currSize < fileSize)
    {
      auto const toRead = std::min(kFileBufferSize, static_cast<uint32_t>(fileSize - currSize));
      file.Read(currSize, buffer, toRead);
      sha1.Update(buffer, toRead);
      currSize += toRead;
    }
    sha1.Final();

    Hash result;
    ASSERT_EQUAL(result.size(), ARRAY_SIZE(sha1.m_digest), ());
    std::copy(std::begin(sha1.m_digest), std::end(sha1.m_digest), std::begin(result));
    return result;
  }
  catch (Reader::Exception const & ex)
  {
    LOG(LERROR, ("Error reading file:", filePath, ex.what()));
  }
  return {};
}

// static
std::string SHA1::CalculateBase64(std::string const & filePath)
{
  auto const sha1 = Calculate(filePath);
  return base64_encode(sha1.data(), sha1.size());
}

// static
SHA1::Hash SHA1::CalculateForString(std::string const & str)
{
  CSHA1 sha1;
  std::vector<unsigned char> dat(str.begin(), str.end());
  sha1.Update(dat.data(), static_cast<uint32_t>(dat.size()));
  sha1.Final();

  Hash result;
  ASSERT_EQUAL(result.size(), ARRAY_SIZE(sha1.m_digest), ());
  std::copy(std::begin(sha1.m_digest), std::end(sha1.m_digest), std::begin(result));
  return result;
}

// static
std::string SHA1::CalculateForStringFormatted(std::string const & str)
{
  auto const hashRaw = CalculateForString(str);

  std::ostringstream os;
  for (auto const value : hashRaw)
    os << std::hex << static_cast<int>(value);

  return os.str();
}

// static
std::string SHA1::CalculateBase64ForString(std::string const & str)
{
  auto const sha1 = CalculateForString(str);
  return base64_encode(sha1.data(), sha1.size());
}
}  // coding