Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Not private in order to prevent optimizations.
- static class Blackhole {
- private static void eat(long n) {
- dummy += n;
- }
- // Not private in order to prevent optimizations.
- static volatile long dummy;
- }
- public boolean areEqual(String input, String secret) {
- final int length = secret.length();
- // No need to keep the length secret.
- if (input.length() != length) {
- return false;
- }
- long delta = 0;
- for (int i = 0; i < length; ++i) {
- // Any char is interpreted as a non-negative number.
- // Xoring such numbers preserves non-negativity.
- // The result depends on every input bit, so no short-circuit is possible.
- // Overflow is impossible, therefore diff is zero <=> all chars are the same.
- delta += input.charAt(i) ^ secret.charAt(i);
- }
- Blackhole.eat(delta);
- return delta == 0;
- }
- int i = 0
- for (; ; ++i) {
- if (input.charAt(i) != secret.charAt(i)) break;
- }
- for (; i < length; ++i) {
- delta += input.charAt(i) ^ secret.charAt(i);
- }
- private static void eat(long n) {
- if (n == dummy) {
- dummy = new SecureRandom().nextLong();
- }
- }
- int differences = 0, matches = 0;
- for (int i = 0; i < length; ++i) {
- if ((input.charAt(i) ^ secret.charAt(i)) != 0)
- ++differences;
- else
- ++matches;
- }
- try
- {
- new SecureRandom().nextLong(differences);
- }
- catch (IllegalArgumentException) {
- // If argument is 0 (what we want for an exact match)
- // then nextLong() throws this exception
- return true;
- }
- return false;
- int differences = 0, i= 0;
- for (i = 0; i < length; ++i) {
- // ...
- }
- if (i != length - 1)
- throw new Exception("..."); // Is it better Error here?
- int differences = 0, matches = 0;
- for (int i = 0; i <= input.length(); ++i) {
- char secretChar = input.charAt(Math.min(input.length() - 1, i));
- if ((input.charAt(i) ^ secretChar) != 0)
- ++differences;
- else
- ++matches;
- }
- new SecureRandom().nextLong(differences + (input.length() ^ secret.length()));
- int secretPasswordHash = Hash(secret);
- public boolean areEqual(String input, String secret) {
- if (secretPasswordHash != Hash(input))
- return false;
- if (input.length() != secret.length())
- return false;
- // With a good hash you really do not need constant-time comparison...
- for (int i = 0; i < input.length(); ++i)
- if (input.charAt(i) != secret.charAt(i))
- return false;
- return true;
- }
- int compareLength = min(a.length(), b.length());
- if (compareLength == 0)
- {
- // at least one string is empty (zero length)
- // so if they're both the same length, both are empty (equal)
- return a.length() == b.length();
- }
- int state = 0;
- for (int i = 0; i < compareLength; i++)
- {
- state |= a.charAt(i) ^ b.charAt(i);
- }
- return state == 0;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement