consttime_memequal.c 694 B

1234567891011121314151617181920212223242526272829
  1. /* $NetBSD: consttime_memequal.c,v 1.6 2015/03/18 20:11:35 riastradh Exp $ */
  2. /*
  3. * Written by Matthias Drochner <drochner@NetBSD.org>.
  4. * Public domain.
  5. */
  6. #include <string.h>
  7. int
  8. consttime_memequal(const void *b1, const void *b2, size_t len)
  9. {
  10. const unsigned char *c1 = b1, *c2 = b2;
  11. unsigned int res = 0;
  12. while (len--)
  13. res |= *c1++ ^ *c2++;
  14. /*
  15. * Map 0 to 1 and [1, 256) to 0 using only constant-time
  16. * arithmetic.
  17. *
  18. * This is not simply `!res' because although many CPUs support
  19. * branchless conditional moves and many compilers will take
  20. * advantage of them, certain compilers generate branches on
  21. * certain CPUs for `!res'.
  22. */
  23. return (1 & ((res - 1) >> 8));
  24. }