summaryrefslogtreecommitdiff
path: root/src/hash_method_openssl.cc
blob: 75f6b8af388f8e2c385e816a2f583de82f8b358b (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
#include "common.hh"

#include "hash_method.hh"

#include <openssl/evp.h>

namespace {

class Sha256HashMethod : public HashMethod {
public:
  Sha256HashMethod() {
    ctx_ = EVP_MD_CTX_new();
    EVP_DigestInit_ex(ctx_, EVP_sha256(), nullptr);
  }

  ~Sha256HashMethod() override {
    EVP_MD_CTX_free(ctx_);
  }

  void update(void const* data, size_t count) override {
    EVP_DigestUpdate(ctx_, data, count);
  }

  std::string finish() override {
    uint8_t out[EVP_MAX_MD_SIZE];
    unsigned int len;
    EVP_DigestFinal_ex(ctx_, out, &len);
    EVP_DigestInit_ex(ctx_, EVP_sha256(), nullptr);
    return to_string(out, len);
  }

private:
  EVP_MD_CTX* ctx_;
};

}  // namespace

std::unique_ptr<HashMethod> HashMethod::sha256() {
  return std::make_unique<Sha256HashMethod>();
}