title: Safety of trying to login (preventing time-attack)
body: <p>I came across a security issue. Please have a look at the pseudocode below</p>
  <pre><code>public static bool TryLogin(string email, string password)
  {
      if (UserExists(email)) // here is the problem
          return false;
  
      var hash = GetRealPasswordHash(email);
      var hash2 = GetHash(email, password);
      return SlowEquals(hash, hash2);
  }
  </code></pre>
  <p>Some of you may already see the hole. An attacker may perform a time-attack over the network - detect how fast the answer is returned and based on that detect if there is a user in the database or not! Having known that, the attacker may now check various passwords for the user he already knows that exists!</p>
  <p>A word of explanation if you don't see the problem or don't believe it to be a problem (this is for hashes, but analogical issue is here):</p>
  <blockquote>
  <p>Comparing the hashes in &quot;length-constant&quot; time ensures that an
  attacker cannot extract the hash of a password in an on-line system
  using a timing attack, then crack it off-line.</p>
  <p>The standard way to check if two sequences of bytes (strings) are the
  same is to compare the first byte, then the second, then the third,
  and so on. As soon as you find a byte that isn't the same for both
  strings, you know they are different and can return a negative
  response immediately. If you make it through both strings without
  finding any bytes that differ, you know the strings are the same and
  can return a positive result. This means that comparing two strings
  can take a different amount of time depending on how much of the
  strings match.</p>
  <p>For example, a standard comparison of the strings &quot;xyzabc&quot; and
  &quot;abcxyz&quot; would immediately see that the first character is different
  and wouldn't bother to check the rest of the string. On the other
  hand, when the strings &quot;aaaaaaaaaaB&quot; and &quot;aaaaaaaaaaZ&quot; are compared,
  the comparison algorithm scans through the block of &quot;a&quot; before it
  determins the strings are unequal.</p>
  <p>It might seem like it would be impossible to run a timing attack over
  a network. However, it has been done, and has been <a href="https://crypto.stanford.edu/%7Edabo/papers/ssl-timing.pdf" rel="nofollow noreferrer">shown to be
  practical</a>.</p>
  <p><a href="https://crackstation.net/hashing-security.htm#normalhashing" rel="nofollow noreferrer">Here you can see the article</a></p>
  </blockquote>
  <p>What should I do then, <strong>when I detect that a user does not exist</strong>? I definitely should perform some more calculations, but what is a good technique here? What do you guys use in such scenarios?</p>
  <p>If this is of any significance, I am using C#.</p>