Skip to content

Instantly share code, notes, and snippets.

@Justasic
Created July 28, 2014 01:27
Show Gist options
  • Save Justasic/2177247266cb2f9e59f1 to your computer and use it in GitHub Desktop.
Save Justasic/2177247266cb2f9e59f1 to your computer and use it in GitHub Desktop.
Some code on doing timing safe string comparison functions made by Aquanight and Attilamolnar from ChatSpike
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <vector>
#include <chrono>
bool AquaConstTimeCMP(const std::string &str1, const std::string &str2)
{
size_t il = str1.length();
size_t tmax = str2.length() - 1;
int ret = 0;
for (size_t n = 0; n < il; ++n)
{
ret |= (str1[n] ^ (n <= tmax ? str2[n] : str2[tmax]));
}
return !ret;
}
bool AttilaConstTimeCMP(const std::string &str1, const std::string &str2)
{
if (str1.length() != str2.length())
return false;
unsigned int ret = 0;
for (std::string::const_iterator i = str1.begin(), j = str2.begin(); i != str1.end(); ++i, ++j)
{
unsigned char a = static_cast<unsigned char>(*i);
unsigned char b = static_cast<unsigned char>(*j);
ret |= a ^ b;
}
return (ret == 0);
}
int main(int argc, char **argv)
{
std::vector<std::string> args(argv, argv+argc);
if (args.size() < 3)
{
printf("Fail\n");
return 0;
}
std::chrono::time_point<std::chrono::system_clock> start, end;
std::chrono::duration<double> elapsed_seconds;
start = std::chrono::system_clock::now();
bool aq = AquaConstTimeCMP(args[1], args[2]);
end = std::chrono::system_clock::now();
elapsed_seconds = end-start;
std::cout << "Result: " << (aq ? "Strings are the same!" : "Strings are different!")
<< " Elapsed seconds: " << elapsed_seconds.count() << "s" << std::endl;
start = std::chrono::system_clock::now();
aq = AttilaConstTimeCMP(args[1], args[2]);
end = std::chrono::system_clock::now();
elapsed_seconds = end-start;
std::cout << "Result: " << (aq ? "Strings are the same!" : "Strings are different!")
<< " Elapsed seconds: " << elapsed_seconds.count() << "s" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment