Comparing Java strings using bitwise xor

I came across the code snippet below in product code. It uses bitwise XOR to compare strings. Is this better than the method String.equals(Object o)? What is the author trying to achieve here?

private static boolean compareSecure(String a, String b)
  {
    if ((a == null) || (b == null)) {
      return (a == null) && (b == null);
    }
    int len = a.length();
    if (len != b.length()) {
      return false;
    }
    if (len == 0) {
      return true;
    }
    int bits = 0;
    for (int i = 0; i < len; i++) {
      bits |= a.charAt(i) ^ b.charAt(i);
    }
    return bits == 0;
  }

In the context, equivalent strings are authentication tokens.

+4
source share

Source: https://habr.com/ru/post/1689282/


All Articles