Constant-time comparison function

Stolen and adapted from:
https://cryptocoding.net/index.php/Coding_rules#Compare_secret_strings_in_constant_time

DON'T MESS WITH THIS FUNCTION

returns boolean true on match, otherwise, false
357885
private function _compareMac($a, $b) {
        $result = "\x00";

        for ($i = 0; $i < $this->_macByteCount; $i++) {
            $result |= substr($a, $i, 1) ^ substr($b, $i, 1);
        }
        
        /* \x00 if equal, nonzero otherwise */
        return ($result === "\x00");
    }
1061454
public static function compare($str1, $str2, $ignoreCase = true)
    {
        if ($ignoreCase) {
            if (strcasecmp($str1, $str2) == 0) {
                return true;
            }
        } else {
            if (strcmp($str1, $str2) == 0) {
                return true;
            }
        }

        return false;
    }
602385
function areThingsEqual (a, b) {
  var aKeys , bKeys , i;

  // Strings, booleans, numbers, null
  if (a === null || typeof a === 'string' || typeof a === 'boolean' || typeof a === 'number' ||
      b === null || typeof b === 'string' || typeof b === 'boolean' || typeof b === 'number') { return a === b; }

  // Dates
  if (util.isDate(a) || util.isDate(b)) { return util.isDate(a) && util.isDate(b) && a.getTime() === b.getTime(); }

  // Arrays (no match since arrays are used as a $in)
  // undefined (no match since they mean field doesn't exist and can't be serialized)
  if ((!(util.isArray(a) && util.isArray(b)) && (util.isArray(a) || util.isArray(b))) || a === undefined || b === undefined) { return false; }

  // General objects (check for deep equality)
  // a and b should be objects at this point
  try {
    aKeys = Object.keys(a);
    bKeys = Object.keys(b);
  } catch (e) {
    return false;
  }

  if (aKeys.length !== bKeys.length) { return false; }
  for (i = 0; i < aKeys.length; i += 1) {
    if (bKeys.indexOf(aKeys[i]) === -1) { return false; }
    if (!areThingsEqual(a[aKeys[i]], b[aKeys[i]])) { return false; }
  }
  return true;
}
862154
private function keysAreEqual($a, $b): bool
    {
        if (is_object($a) && $a instanceof Hashable) {
            return get_class($a) === get_class($b) && $a->equals($b);
        }

        return $a === $b;
    }
850684
public static function equals($knownString, $userInput)
    {
        if (!is_string($knownString)) {
            $knownString = (string)$knownString;
        }

        if (!is_string($userInput)) {
            $userInput = (string)$userInput;
        }

        if (function_exists('hash_equals')) {
            return hash_equals($knownString, $userInput);
        }

        $knownLength = mb_strlen($knownString);

        if (mb_strlen($userInput) !== $knownLength) {
            return false;
        }

        $result = 0;

        for ($i = 0; $i < $knownLength; ++$i) {
            $result |= (ord($knownString[$i]) ^ ord($userInput[$i]));
        }

        return 0 === $result;
    }
559028
function verifyHeader (currentHash, currentHeader, hashPrevBlock, prevHeader, target, isTestnet) {
  try {
    // check hashPrevBlock
    assert.equal(hashPrevBlock, currentHeader.hashPrevBlock)

    try {
      // check difficulty
      assert.equal(currentHeader.bits, target.bits)
      // check hash and target
      assert.equal(isGoodHash(currentHash, target.target), true)

    } catch (err) {
      // special case for testnet:
      // If no block has been found in 20 minutes, the difficulty automatically
      //  resets back to the minimum for a single block, after which it returns
      //  to its previous value.
      if (!(err instanceof assert.AssertionError &&
            isTestnet &&
            currentHeader.time - prevHeader.time > 1200)) {
        throw err
      }

      assert.equal(currentHeader.bits, MAX_BITS)
      assert.equal(isGoodHash(currentHash, MAX_TARGET), true)
    }
  } catch (err) {
    if (err instanceof assert.AssertionError) {
      throw new errors.Blockchain.VerifyHeaderError(currentHash, 'verification failed')
    }

    throw err
  }
}
349819
function _rsaes_pkcs1_v1_5_encrypt($m)
    {
        $mLen = strlen($m);

        // Length checking

        if ($mLen > $this->k - 11) {
            user_error('Message too long');
            return false;
        }

        // EME-PKCS1-v1_5 encoding

        $psLen = $this->k - $mLen - 3;
        $ps = '';
        while (strlen($ps) != $psLen) {
            $temp = crypt_random_string($psLen - strlen($ps));
            $temp = str_replace("\x00", '', $temp);
            $ps.= $temp;
        }
        $type = 2;
        // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
        if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
            $type = 1;
            // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
            $ps = str_repeat("\xFF", $psLen);
        }
        $em = chr(0) . chr($type) . $ps . chr(0) . $m;

        // RSA encryption
        $m = $this->_os2ip($em);
        $c = $this->_rsaep($m);
        $c = $this->_i2osp($c, $this->k);

        // Output the ciphertext C

        return $c;
    }
865169
private function codeEquals($safe, $user) {
        if (function_exists('hash_equals')) {
            return hash_equals($safe, $user);
        }
        // In general, it's not possible to prevent length leaks. So it's OK to leak the length. The important part is that
        // we don't leak information about the difference of the two strings.
        if (strlen($safe)===strlen($user)) {
            $result = 0;
            for ($i = 0; $i < strlen($safe); $i++)
                $result |= (ord($safe[$i]) ^ ord($user[$i]));
            return $result === 0;
        }
        return false;
    }
1352917
def is_equal(self, string1, string2):
        '''  '''
        return string1.lower().strip() == string2.lower().strip()
1045645
def compare_checksum(info, f):
    
    pieces = info['pieces']

    def getchunks(f, size):
        while True:
            chunk = f.read(size)
            if chunk == '':
                break
            yield hashlib.sha1(chunk).digest()

    calc = getchunks(f, info['piece length'])
    ref = (pieces[i:i + 20] for i in xrange(0, len(pieces), 20))
    for expected, actual in itertools.izip(calc, ref):
        if expected != actual:
            return False
    return ensure_empty(calc) and ensure_empty(ref)
1316912
def constant_time_cmp(a, b):
    ''''''
    result = True
    for x, y in zip(a, b):
        result &= (x == y)
    return result
989316
public boolean isEncryptedString( final String str )
    {
        if ( str == null || str.length() < 1 )
        {
            return false;
        }

        Matcher matcher = ENCRYPTED_STRING_PATTERN.matcher( str );

        return matcher.matches() || matcher.find();
    }
916774
def _safe_str_cmp(a, b):
    
    if len(a) != len(b):
        return False
    rv = 0
    for x, y in zip(a, b):
        rv |= ord(x) ^ ord(y)
    return rv == 0
1098183
function decrypt($ciphertext)
    {
        if ($this->k <= 0) {
            return false;
        }

        $ciphertext = str_split($ciphertext, $this->k);
        $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT);

        $plaintext = '';

        switch ($this->encryptionMode) {
            case CRYPT_RSA_ENCRYPTION_NONE:
                $decrypt = '_raw_encrypt';
                break;
            case CRYPT_RSA_ENCRYPTION_PKCS1:
                $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
                break;
            //case CRYPT_RSA_ENCRYPTION_OAEP:
            default:
                $decrypt = '_rsaes_oaep_decrypt';
        }

        foreach ($ciphertext as $c) {
            $temp = $this->$decrypt($c);
            if ($temp === false) {
                return false;
            }
            $plaintext.= $temp;
        }

        return $plaintext;
    }
568598
public function checkTotp($secret, $key, $timedrift = 1)
    {
        if (!is_numeric($timedrift) || $timedrift < 0) {
            throw new \InvalidArgumentException('Invalid timedrift supplied');
        }
        // Counter comes from time now
        // Also we check the current timestamp as well as previous and future ones
        // according to $timerange
        $timecounter = $this->getTimecounter();
    
        $start = $timecounter - ($timedrift);
        $end = $timecounter + ($timedrift);
    
        // We first try the current, as it is the most likely to work
        if (hash_equals($this->totp($secret, $timecounter), $key)) {
            return true;
        } elseif ($timedrift == 0) {
            // When timedrift is 0, this is the end of the checks
            return false;
        }
    
        // Well, that didn't work, so try the others
        for ($t = $start; $t <= $end; $t = $t + 1) {
            if ($t == $timecounter) {
                // Already tried that one
                continue;
            }
                
            if (hash_equals($this->totp($secret, $t), $key)) {
                return true;
            }
        }
    
        // if none worked, then return false
        return false;
    }
1070243
def secure_compare(a, b)
        if a.length == b.length
          result = 0
          for i in 0..(a.length - 1)
            result |= a[i] ^ b[i]
          end
          result == 0
        else
          false
        end
      end
873440
@SuppressWarnings("unused")
    public static boolean isTokenValid(byte[] secret, String oid, String token) {
        if (S.anyBlank(oid, token)) {
            return false;
        }
        String s = Crypto.decryptAES(token, secret);
        String[] sa = s.split("\\|");
        if (sa.length < 2) return false;
        if (!S.isEqual(oid, sa[0])) return false;
        try {
            long due = Long.parseLong(sa[1]);
            return (due < 1 || due > System.currentTimeMillis());
        } catch (Exception e) {
            return false;
        }
    }