memory: Add helper function to conditionally copy data in constant time
This commit is contained in:
@@ -90,6 +90,27 @@ bool memeq_const(const void *x, const void *y, size_t len)
|
||||
return !bad;
|
||||
}
|
||||
|
||||
/*
|
||||
* Described in header
|
||||
*/
|
||||
void memcpy_cond(void *dst, const void *src, size_t n, uint8_t cond)
|
||||
{
|
||||
uint8_t *a;
|
||||
const uint8_t *b;
|
||||
size_t i;
|
||||
|
||||
a = (uint8_t*)dst;
|
||||
b = (const uint8_t*)src;
|
||||
|
||||
/* either 0xff or 0 */
|
||||
cond = -cond;
|
||||
|
||||
for (i = 0; i < n; i++)
|
||||
{
|
||||
a[i] ^= cond & (a[i] ^ b[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Described in header.
|
||||
*/
|
||||
|
||||
@@ -54,6 +54,15 @@ static inline void *memcpy_noop(void *dst, const void *src, size_t n)
|
||||
#endif
|
||||
#define memcpy(d,s,n) memcpy_noop(d,s,n)
|
||||
|
||||
/**
|
||||
* Copies n bytes from src to dst if the given condition is 1, or leaves dst
|
||||
* unchanged if it's 0 (but does write to it).
|
||||
*
|
||||
* Runs in constant time, so it's safe to conditionally copy data after a call
|
||||
* to memeq_const() without any branching instructions.
|
||||
*/
|
||||
void memcpy_cond(void *dst, const void *src, size_t n, uint8_t cond);
|
||||
|
||||
/**
|
||||
* Calling memmove() with NULL pointers, even with n == 0, results in undefined
|
||||
* behavior according to the C standard. This version is guaranteed to not
|
||||
|
||||
Reference in New Issue
Block a user