Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Today, I asked Google if there was a constant time string comparison algorithm in the JRE. It told me "no, but you can roll your own". Then I perused the links and found that MessageDigest.isEqual exists.


Are you sure it was wrong? I haven't used Java in over a decade, but looking at the docs for that method, I see it is only define for byte arrays, not strings.

That's also what Grok says:

> Is there a constant time string comparison algorithm in the JRE?

No, the Java Runtime Environment (JRE) does not provide a built-in constant-time comparison method directly for String objects in the standard library. The String.equals() and String.equalsIgnoreCase() methods perform variable-time comparisons that short-circuit upon finding the first mismatch, which can be vulnerable to timing attacks in security-sensitive contexts like password or token verification. However, the JRE does include a constant-time comparison utility for byte arrays via java.security.MessageDigest.isEqual(byte[] digesta, byte[] digestb), introduced in Java 6 and documented as performing a comparison where "the calculation time depends only on the length of digesta [and] does not depend on the ... contents." This makes it suitable for secure comparisons against timing side-channel attacks. To use it for strings:

Convert both strings to byte arrays using a consistent encoding (e.g., UTF-8 via getBytes("UTF-8")). Ensure the byte arrays have the same length first (as the method requires equal-length inputs for meaningful results). Call MessageDigest.isEqual() on the arrays.


Strings _are_ bytes under the hood - this is the kind of "well, technically it's not wrong" that makes "ask an LLM" nothing like "Ask Linus" or even "Ask the intern".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: