Skip to content

Instantly share code, notes, and snippets.

@gcmurphy
Created September 2, 2014 03:48
Show Gist options
  • Save gcmurphy/dc41732875bf1c61a939 to your computer and use it in GitHub Desktop.
Save gcmurphy/dc41732875bf1c61a939 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
bool constant_time_compare(const char *lhs, size_t lhs_sz, const char *rhs, size_t rhs_sz)
{
size_t i;
uint64_t r = 0;
if (lhs_sz != rhs_sz){
return false;
}
for (i = 0; i < lhs_sz; ++i){
r |= lhs[i] ^ rhs[i];
}
return r == 0;
}
int main()
{
const char *user_supplied_hmac_bad = "wrong shit";
const char *user_supplied_hmac_good = "foobar";
const char *calculated_hmac = "foobar";
/* note:
* strlen here is for testing in practice length
* would be known and O(1) lookup
*/
/* expect constant time compare fail */
assert (! constant_time_compare(
calculated_hmac,
strlen(calculated_hmac),
user_supplied_hmac_bad,
strlen(user_supplied_hmac_bad) ));
/* expect constant time compare pass */
assert (constant_time_compare(
calculated_hmac,
strlen(calculated_hmac),
user_supplied_hmac_good,
strlen(user_supplied_hmac_good) ) );
puts("ok");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment