blob: 86cf25969b452ace15899a8936d052f67d39921e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
/*
* Timing Attack Countermeasure Functions
* (C) 2010 Falko Strenzke, Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/internal/ta_utils.h>
namespace Botan {
namespace TA_CM {
/*
* We use volatile in these functions in an attempt to ensure that the
* compiler doesn't optimize in a way that would create branching
* operations.
*
* Note: this needs further testing; on at least x86-64 with GCC,
* volatile is not required to get branch-free operations, it just
* makes the functions much longer/slower. It may not be required
* anywhere.
*/
u32bit gen_mask_u32bit(u32bit in)
{
volatile u32bit result = in;
result |= result >> 1;
result |= result >> 2;
result |= result >> 4;
result |= result >> 8;
result |= result >> 16;
result &= 1;
result = ~(result - 1);
return result;
}
u32bit max_32(u32bit a, u32bit b)
{
const u32bit a_larger = b - a; /* negative if a larger */
const u32bit mask = gen_mask_u32bit(a_larger >> 31);
return (a & mask) | (b & ~mask);
}
u32bit min_32(u32bit a, u32bit b)
{
const u32bit a_larger = b - a; /* negative if a larger */
const u32bit mask = gen_mask_u32bit(a_larger >> 31);
return (a & ~mask) | (b & mask);
}
}
}
|