1//
2// DigestEngine.h
3//
4// Library: Foundation
5// Package: Crypt
6// Module: DigestEngine
7//
8// Definition of class DigestEngine.
9//
10// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
11// and Contributors.
12//
13// SPDX-License-Identifier: BSL-1.0
14//
15
16
17#ifndef Foundation_DigestEngine_INCLUDED
18#define Foundation_DigestEngine_INCLUDED
19
20
21#include "Poco/Foundation.h"
22#include <vector>
23
24
25namespace Poco {
26
27
28class Foundation_API DigestEngine
29 /// This class is an abstract base class
30 /// for all classes implementing a message
31 /// digest algorithm, like MD5Engine
32 /// and SHA1Engine.
33 /// Call update() repeatedly with data to
34 /// compute the digest from. When done,
35 /// call digest() to obtain the message
36 /// digest.
37{
38public:
39 typedef std::vector<unsigned char> Digest;
40
41 DigestEngine();
42 virtual ~DigestEngine();
43
44 void update(const void* data, std::size_t length);
45 void update(char data);
46 void update(const std::string& data);
47 /// Updates the digest with the given data.
48
49 virtual std::size_t digestLength() const = 0;
50 /// Returns the length of the digest in bytes.
51
52 virtual void reset() = 0;
53 /// Resets the engine so that a new
54 /// digest can be computed.
55
56 virtual const Digest& digest() = 0;
57 /// Finishes the computation of the digest and
58 /// returns the message digest. Resets the engine
59 /// and can thus only be called once for every digest.
60 /// The returned reference is valid until the next
61 /// time digest() is called, or the engine object is destroyed.
62
63 static std::string digestToHex(const Digest& bytes);
64 /// Converts a message digest into a string of hexadecimal numbers.
65
66 static Digest digestFromHex(const std::string& digest);
67 /// Converts a string created by digestToHex back to its Digest presentation
68
69 static bool constantTimeEquals(const Digest& d1, const Digest& d2);
70 /// Compares two Digest values using a constant-time comparison
71 /// algorithm. This can be used to prevent timing attacks
72 /// (as discussed in <https://codahale.com/a-lesson-in-timing-attacks/>).
73
74protected:
75 virtual void updateImpl(const void* data, std::size_t length) = 0;
76 /// Updates the digest with the given data. Must be implemented
77 /// by subclasses.
78
79private:
80 DigestEngine(const DigestEngine&);
81 DigestEngine& operator = (const DigestEngine&);
82};
83
84
85//
86// inlines
87//
88
89
90inline void DigestEngine::update(const void* data, std::size_t length)
91{
92 updateImpl(data, length);
93}
94
95
96inline void DigestEngine::update(char data)
97{
98 updateImpl(&data, 1);
99}
100
101
102inline void DigestEngine::update(const std::string& data)
103{
104 updateImpl(data.data(), data.size());
105}
106
107
108} // namespace Poco
109
110
111#endif // Foundation_DigestEngine_INCLUDED
112