Why Constant-Time String Comparison Matters: Preventing Timing Attacks

The article explains how constant‑time string comparison functions work, shows Java and Scala implementations, and demonstrates why such techniques are essential to thwart timing attacks in cryptographic and authentication scenarios.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Why Constant-Time String Comparison Matters: Preventing Timing Attacks

Understanding Constant‑Time Comparison

The article starts with a Java implementation of safeEqual(String a, String b) that first checks length equality, then iterates over each character, XOR‑ing the bytes and accumulating the result with a bitwise OR. If the final accumulated value is zero, the strings are equal.

boolean safeEqual(String a, String b) {
    if (a.length() != b.length()) {
        return false;
    }
    int equal = 0;
    for (int i = 0; i < a.length(); i++) {
        equal |= a.charAt(i) ^ b.charAt(i);
    }
    return equal == 0;
}

The same logic is shown in Scala, where the function uses def safeEqual(a: String, b: String) = { ... } with a similar XOR‑and‑OR approach.

def safeEqual(a: String, b: String) = {
  if (a.length != b.length) {
    false
  } else {
    var equal = 0
    for (i <- Array.range(0, a.length)) {
      equal |= a(i) ^ b(i)
    }
    equal == 0
  }
}

Why Not Return Early?

Although returning immediately when a mismatched byte is found would be more efficient, the article explains that the function deliberately avoids early exit to keep execution time independent of the data, thereby preventing timing side‑channel leaks.

JDK Example

The Java standard library provides a similar constant‑time method in java.security.MessageDigest.isEqual:

public static boolean isEqual(byte[] digesta, byte[] digestb) {
    if (digesta == digestb) return true;
    if (digesta == null || digestb == null) return false;
    if (digesta.length != digestb.length) return false;
    int result = 0;
    for (int i = 0; i < digesta.length; i++) {
        result |= digesta[i] ^ digestb[i];
    }
    return result == 0;
}

The comment notes that the comparison runs in constant time.

What Is a Timing Attack?

A timing attack is a form of side‑channel attack that measures the time taken by cryptographic operations to infer secret data. By ensuring that string‑comparison functions always take the same amount of time, attackers cannot distinguish between matching and non‑matching inputs.

For example, comparing safeEquals("abcdefghijklmn", "xbcdefghijklmn") (first character differs) and safeEquals("abcdefghijklmn", "abcdefghijklmn") (identical) should consume equal time, preventing an attacker from guessing passwords character by character.

Real‑World Relevance

The article cites PHP’s hash_equals and password_verify as safe‑comparison functions, and mentions that many languages and frameworks (e.g., OpenSSL, Play) adopt the same constant‑time technique.

It also references a historical vulnerability in JDK 1.6.0_17 where MessageDigest.isEqual was fixed to address timing‑attack risks, showing the associated bug‑fix diff images.

Are Timing Attacks Practical?

Academic research, such as the paper “Remote Timing Attacks are Practical”, demonstrates that timing attacks can break RSA keys in OpenSSL over the network, confirming the real‑world threat and motivating the adoption of constant‑time APIs.

The author concludes that while measuring execution time in practice can be noisy, defending against timing attacks remains essential for any security‑critical code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javainformation securitycryptographytiming attackconstant-time comparisonsecure string comparison
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.