Notes on constant-time crypto
Some notes on learning/using constant-time cryptography.
- Constant-Time Arithmetic for Safer Cryptography
- constant-time arbitrary-precision arithmetic operations
- constant-time programs - operations vary in time based only on public values
- examples
- replacing branches with bitwise operations
- avoiding array accesses with secret indices
- making sure that loops have a fixed number of iterations
- modern crypto
- finite fields with fixed parameters (eg. ECC)
- traditional crypto
- not fixed parameter (eg. RSA)
saferithas a constant-time alternative to Go’sbig.Int- problem: traditional libraries store numbers without zero padding
- solution: pad numbers to different public sizes
- leaks public sizes, while still keeping values hidden
- Timing attack in Google’s Keyczar lib
- Example of constant-time string comparison
1 correctMac = self.Sign(msg) 2 if len(correctMac) != len(sig_bytes): 3 return False 4 result = 0 5 for x, y in zip(correctMac, sig_bytes): 6 result |= ord(x) ^ ord(y) 7 return result == 0
- Example of constant-time string comparison
- Guidelines for low-level cryptography software | Cryptocoding | Jean-Philippe Aumasson
- Go’s crypto/subtle library: implements functions that are often useful in cryptographic code but require careful thought to use correctly
- Select between a and b without using
if-else.1/* Conditionally return a or b depending on whether bit is set */ 2/* Equivalent to: return bit ? a : b */ 3unsigned select (unsigned a, unsigned b, unsigned bit) 4{ 5 unsigned isnonzero = (bit | -bit) >> (sizeof(unsigned) * CHAR_BIT - 1); 6 /* -0 = 0, -1 = 0xff....ff */ 7 unsigned mask = -isnonzero; 8 unsigned ret = mask & (b^a); 9 ret = ret ^ b; 10 return ret; 11}- Only if bit is 0, the (bit | -bit) will result in MSB (isnonzero) equal to 0. In all other cases, MSB (isnonzero) is equal to 1.
- If mask is 0 we return b, else if mask is 1 we return a.
- Avoid secret-dependent loop bounds
- Clean memory of secret data
- Unfortunately, there’s virtually no way to reliably clean secret data in garbage-collected languages (such as Go), nor in language with immutable strings.
- https://github.com/cronokirby/saferith
More links