mirror of
https://github.com/pocoproject/poco.git
synced 2025-02-02 15:24:57 +01:00
GH #1412: added Poco::DigestEngine::constantTimeEquals()
This commit is contained in:
parent
0db79db029
commit
bdbc94d825
@ -66,6 +66,11 @@ public:
|
||||
static Digest digestFromHex(const std::string& digest);
|
||||
/// Converts a string created by digestToHex back to its Digest presentation
|
||||
|
||||
static bool constantTimeEquals(const Digest& d1, const Digest& d2);
|
||||
/// Compares two Digest values using a constant-time comparison
|
||||
/// algorithm. This can be used to prevent timing attacks
|
||||
/// (as discussed in <https://codahale.com/a-lesson-in-timing-attacks/>).
|
||||
|
||||
protected:
|
||||
virtual void updateImpl(const void* data, std::size_t length) = 0;
|
||||
/// Updates the digest with the given data. Must be implemented
|
||||
|
@ -79,5 +79,21 @@ DigestEngine::Digest DigestEngine::digestFromHex(const std::string& digest)
|
||||
}
|
||||
|
||||
|
||||
bool DigestEngine::constantTimeEquals(const Digest& d1, const Digest& d2)
|
||||
{
|
||||
if (d1.size() != d2.size()) return false;
|
||||
|
||||
int result = 0;
|
||||
Digest::const_iterator it1 = d1.begin();
|
||||
Digest::const_iterator it2 = d2.begin();
|
||||
Digest::const_iterator end1 = d1.end();
|
||||
while (it1 != end1)
|
||||
{
|
||||
result |= *it1++ ^ *it2++;
|
||||
}
|
||||
return result == 0;
|
||||
}
|
||||
|
||||
|
||||
} // namespace Poco
|
||||
|
||||
|
@ -58,6 +58,17 @@ void MD5EngineTest::testMD5()
|
||||
}
|
||||
|
||||
|
||||
void MD5EngineTest::testConstantTimeEquals()
|
||||
{
|
||||
DigestEngine::Digest d1 = DigestEngine::digestFromHex("d41d8cd98f00b204e9800998ecf8427e");
|
||||
DigestEngine::Digest d2 = DigestEngine::digestFromHex("d41d8cd98f00b204e9800998ecf8427e");
|
||||
DigestEngine::Digest d3 = DigestEngine::digestFromHex("0cc175b9c0f1b6a831c399e269772661");
|
||||
|
||||
assert (DigestEngine::constantTimeEquals(d1, d2));
|
||||
assert (!DigestEngine::constantTimeEquals(d1, d3));
|
||||
}
|
||||
|
||||
|
||||
void MD5EngineTest::setUp()
|
||||
{
|
||||
}
|
||||
@ -73,6 +84,7 @@ CppUnit::Test* MD5EngineTest::suite()
|
||||
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MD5EngineTest");
|
||||
|
||||
CppUnit_addTest(pSuite, MD5EngineTest, testMD5);
|
||||
CppUnit_addTest(pSuite, MD5EngineTest, testConstantTimeEquals);
|
||||
|
||||
return pSuite;
|
||||
}
|
||||
|
@ -25,6 +25,7 @@ public:
|
||||
~MD5EngineTest();
|
||||
|
||||
void testMD5();
|
||||
void testConstantTimeEquals();
|
||||
|
||||
void setUp();
|
||||
void tearDown();
|
||||
|
Loading…
x
Reference in New Issue
Block a user