In C++, constant-time comparisons are useful for securely comparing sensitive data, such as passwords or cryptographic keys, to prevent timing attacks. A common approach is to use a method that ensures both inputs are processed in the same amount of time, regardless of their content.
The `std::equal` function can be employed for this purpose, where you compare two strings character by character. This ensures that the comparison takes the same time whether the strings match or not.
Below is a simple example demonstrating how to implement constant-time string comparison in C++:
#include <iostream>
#include <string>
#include <algorithm>
bool constant_time_compare(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return false;
volatile unsigned char result = 0; // Prevent optimization
for (size_t i = 0; i < a.size(); ++i) {
result |= a[i] ^ b[i];
}
return result == 0;
}
int main() {
std::string password = "secret";
std::string input;
std::cout << "Enter password: ";
std::cin >> input;
if (constant_time_compare(password, input)) {
std::cout << "Access granted!" << std::endl;
} else {
std::cout << "Access denied!" << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?