liveBook · Manning

Constant-time programming

As explained in Real-World Cryptography

A constant-time algorithm executes in a pattern whose duration does not depend on secret data.

Constant-time programming keeps cryptographic work on the same execution path regardless of secret input. Avoiding secret-dependent branches helps resist timing, cache, and simple power-analysis attacks. section 13.4.1 section 13.5

Practical patterns include:

  • Compare authentication tags by XORing corresponding bytes and accumulating the differences with OR, then check the final result. section 13.4.1
  • Use algorithms that always perform both alternatives, such as Montgomery’s ladder or RSA square-and-multiply-always. section 13.4.1
  • Avoid memory accesses that depend on secret data, not only conditional branches. section 13.5
Listing 13.1 How Golang implements a constant-time comparison between two bytearrays
func ConstantTimeCompare(x, y []byte) byte {
    if len(x) != len(y) {                        #1
        return 0                                 #1
    }                                            #1
 
    var v byte                                   #2
    for i := 0; i < len(x); i++ {                #2
        v |= x[i] ^ y[i]                         #2
    }                                            #2
 
    return v                                     #3
}

A small Go comparison routine makes the XOR-and-OR accumulation pattern concrete. section 13.4.1

How Real-World Cryptography covers it

How deep it goes
Explains branch-free comparisons and algorithmic patterns, while stopping short of formal proofs or implementation-level completeness.
Examples
Uses Go authentication-tag comparison, Montgomery’s ladder, and RSA square-and-multiply-always.
What it assumes
Assumes basic cryptographic operations and secret data, while explaining the core branch-free idea directly.
What you can do after
Apply it by removing secret-dependent branches and memory accesses from cryptographic implementations.
How it connects
Connects side-channel attacks with cache attacks, power analysis, masking, blinding, and fault-attack mitigation.

Also explained in

Compare how 2 books explain constant-time programming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Real-World Cryptography. The section links point to the parts of the book it draws on.