smemeq.c 818 B

1234567891011121314151617181920212223242526
  1. /*
  2. * Compare two fixed-size regions of memory, in a crypto-safe way,
  3. * i.e. without timing or cache side channels indicating anything
  4. * about what the answer was or where the first difference (if any)
  5. * might have been.
  6. */
  7. #include "defs.h"
  8. #include "misc.h"
  9. unsigned smemeq(const void *av, const void *bv, size_t len)
  10. {
  11. const unsigned char *a = (const unsigned char *)av;
  12. const unsigned char *b = (const unsigned char *)bv;
  13. unsigned val = 0;
  14. while (len-- > 0) {
  15. val |= *a++ ^ *b++;
  16. }
  17. /* Now val is 0 iff we want to return 1, and in the range
  18. * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
  19. * will clear bit 8 iff we want to return 0, and leave it set iff
  20. * we want to return 1, so then we can just shift down. */
  21. return (0x100 - val) >> 8;
  22. }