From 8d6ca210d067fecc58ff6040935bd53d5e66bf64 Mon Sep 17 00:00:00 2001 From: heck Date: Mon, 28 Feb 2022 23:24:49 +0100 Subject: [PATCH] Import: module 'constant_time_algo' from libpEpAdapter --- src/constant_time_algo.cc | 21 +++++++++++++++++++++ src/constant_time_algo.hh | 19 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 src/constant_time_algo.cc create mode 100644 src/constant_time_algo.hh diff --git a/src/constant_time_algo.cc b/src/constant_time_algo.cc new file mode 100644 index 0000000..582cf0e --- /dev/null +++ b/src/constant_time_algo.cc @@ -0,0 +1,21 @@ +// This file is under GNU General Public License 3.0 +// see LICENSE.txt + +#include "constant_time_algo.hh" + +namespace pEp { + bool constant_time_equal(const std::string &a, const std::string &b) + { + if (a.size() != b.size()) + return false; + + unsigned d = 0; + for (std::size_t idx = 0; idx < a.size(); ++idx) { + d |= (static_cast(a[idx]) ^ static_cast(b[idx])); + } + + // if d is still 0, the strings are equal. + return d == 0; + } + +} // end of namespace pEp diff --git a/src/constant_time_algo.hh b/src/constant_time_algo.hh new file mode 100644 index 0000000..c9e5733 --- /dev/null +++ b/src/constant_time_algo.hh @@ -0,0 +1,19 @@ +// This file is under GNU General Public License 3.0 +// see LICENSE.txt + +#ifndef LIBPEPADAPTER_CONSTANT_TIME_ALGO_HH +#define LIBPEPADAPTER_CONSTANT_TIME_ALGO_HH + +#include + +namespace pEp { + // Returns false if a.size() != b.size(). + // Compares always _all_ characters of 'a' and 'b' so runtime does not + // depends on the character position where the strings differ. + // Use this function instead of operator== if timing sidechannel attack + // might be a security problem. + bool constant_time_equal(const std::string &a, const std::string &b); + +} // end of namespace pEp + +#endif // LIBPEPADAPTER_CONSTANT_TIME_ALGO_HH