Botan  1.11.15
src/lib/utils/ta_utils.cpp
Go to the documentation of this file.
00001 /*
00002 * Timing Attack Countermeasure Functions
00003 * (C) 2010 Falko Strenzke, Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #include <botan/internal/ta_utils.h>
00009 
00010 namespace Botan {
00011 
00012 namespace TA_CM {
00013 
00014 /*
00015 * We use volatile in these functions in an attempt to ensure that the
00016 * compiler doesn't optimize in a way that would create branching
00017 * operations.
00018 *
00019 * Note: this needs further testing; on at least x86-64 with GCC,
00020 * volatile is not required to get branch-free operations, it just
00021 * makes the functions much longer/slower. It may not be required
00022 * anywhere.
00023 */
00024 
00025 namespace {
00026 
00027 template<typename T>
00028 T expand_mask(T x)
00029    {
00030    volatile T r = x;
00031    for(size_t i = 1; i != sizeof(T) * 8; i *= 2)
00032       r |= r >> i;
00033    r &= 1;
00034    r = ~(r - 1);
00035    return r;
00036    }
00037 
00038 }
00039 
00040 u32bit expand_mask_u32bit(u32bit in)
00041    {
00042    return expand_mask<u32bit>(in);
00043    }
00044 
00045 u16bit expand_mask_u16bit(u16bit in)
00046    {
00047    return expand_mask<u16bit>(in);
00048    }
00049 
00050 u32bit max_32(u32bit a, u32bit b)
00051    {
00052    const u32bit a_larger = b - a; /* negative if a larger */
00053    const u32bit mask = expand_mask<u32bit>(a_larger >> 31);
00054    return (a & mask) | (b & ~mask);
00055    }
00056 
00057 u32bit min_32(u32bit a, u32bit b)
00058    {
00059    const u32bit a_larger = b - a; /* negative if a larger */
00060    const u32bit mask = expand_mask<u32bit>(a_larger >> 31);
00061    return (a & ~mask) | (b & mask);
00062    }
00063 
00064 }
00065 
00066 }