kodi
Digest.h
1 /*
2  * Copyright (C) 2018 Team Kodi
3  * This file is part of Kodi - https://kodi.tv
4  *
5  * SPDX-License-Identifier: GPL-2.0-or-later
6  * See LICENSES/README.md for more information.
7  */
8 
9 #pragma once
10 
11 #include "StringUtils.h"
12 
13 #include <iostream>
14 #include <memory>
15 #include <stdexcept>
16 #include <string>
17 
18 #include <openssl/evp.h>
19 
20 namespace KODI
21 {
22 namespace UTILITY
23 {
24 
28 class CDigest
29 {
30 public:
31  enum class Type
32  {
33  MD5,
34  SHA1,
35  SHA256,
36  SHA512,
37  INVALID
38  };
39 
43  static std::string TypeToString(Type type);
47  static Type TypeFromString(std::string const& type);
48 
52  CDigest(Type type);
58  void Update(std::string const& data);
64  void Update(void const* data, std::size_t size);
73  std::string Finalize();
82  std::string FinalizeRaw();
83 
87  static std::string Calculate(Type type, std::string const& data);
91  static std::string Calculate(Type type, void const* data, std::size_t size);
92 
93 private:
94  struct MdCtxDeleter
95  {
96  void operator()(EVP_MD_CTX* context);
97  };
98 
99  bool m_finalized{false};
100  std::unique_ptr<EVP_MD_CTX, MdCtxDeleter> m_context;
101  EVP_MD const* m_md;
102 };
103 
105 {
106  CDigest::Type type{CDigest::Type::INVALID};
107  std::string value;
108 
109  TypedDigest() = default;
110 
111  TypedDigest(CDigest::Type type, std::string const& value)
112  : type(type), value(value)
113  {}
114 
115  bool Empty() const
116  {
117  return (type == CDigest::Type::INVALID || value.empty());
118  }
119 };
120 
121 inline bool operator==(TypedDigest const& left, TypedDigest const& right)
122 {
123  if (left.type != right.type)
124  {
125  throw std::logic_error("Cannot compare digests of different type");
126  }
127  return StringUtils::EqualsNoCase(left.value, right.value);
128 }
129 
130 inline bool operator!=(TypedDigest const& left, TypedDigest const& right)
131 {
132  return !(left == right);
133 }
134 
135 std::ostream& operator<<(std::ostream& os, TypedDigest const& digest);
136 
137 }
138 }
void Update(std::string const &data)
Update digest with data.
Definition: Digest.cpp:109
static std::string Calculate(Type type, std::string const &data)
Calculate message digest.
Definition: Digest.cpp:154
CDigest(Type type)
Create a digest calculation object.
Definition: Digest.cpp:100
std::string FinalizeRaw()
Finalize and return the digest.
Definition: Digest.cpp:127
static std::string TypeToString(Type type)
Convert type enumeration value to lower-case string representation.
Definition: Digest.cpp:50
static Type TypeFromString(std::string const &type)
Convert digest type string representation to enumeration value.
Definition: Digest.cpp:69
std::string Finalize()
Finalize and return the digest.
Definition: Digest.cpp:149
Utility class for calculating message digests/hashes, currently using OpenSSL.
Definition: Digest.h:28
Definition: AudioDecoder.h:18
Definition: Digest.h:104