Implements equality between strings which run in constant time by either comparing the sizes, and thus ignoring their content, or checking the whole content of them, thus avoiding timing attacks when comparing hashes.
| 164 | // comparing the sizes, and thus ignoring their content, or checking the whole |
| 165 | // content of them, thus avoiding timing attacks when comparing hashes. |
| 166 | bool constantTimeEquals(const string& left, const string& right) |
| 167 | { |
| 168 | if (left.size() != right.size()) { |
| 169 | return false; |
| 170 | } |
| 171 | |
| 172 | unsigned valid = 0; |
| 173 | for (size_t i = 0; i < left.size(); ++i) { |
| 174 | valid |= left[i] ^ right[i]; |
| 175 | } |
| 176 | |
| 177 | return valid == 0; |
| 178 | } |
| 179 | |
| 180 | } // namespace { |
| 181 |