title: How do I implement a string comparison in Java that takes the same amount of time no matter whether they match or where a mismatch (if any) occurs?
body: <p>I want to implement a <code>String</code> comparison function that doesn't take a different amount of time depending on the number of characters that match or the position of the first mismatch. I assume there must be a library out there somewhere that provides this, but I was unable to find it via a quick search.</p>
  
  <p>So far, the best idea I've got is to sum the XOR of each character and return whether or not the sum is <code>0</code>. However, I'm pretty sure this wouldn't work so well with Unicode. I also have a vague concern that HotSpot would do some optimizations that would change my constant-time property, but I can't think of a specific optimization that would do this off the top of my head.</p>
  
  <p>Thanks.</p>
  
  <p>UPDATE: Sorry, I don't believe I was clear. I'm not looking for <code>O(1)</code>, I'm looking for something that won't leak timing information. This would be used to compare hashed password values, and if the time it took to compare was different based on where the first mismatch occurred, that would be leaking information to an attacker.</p>