title: Why can bcrypt.hashpw be used both for hashing and verifying passwords?
body: <p>Using <a href="https://github.com/dstufft/bcrypt" rel="noreferrer"><code>bcrypt</code></a> with Python 2.7, I can see that the example uses the <code>bcrypt.hashpw</code> to both hash a password for storage and verify that the given password matches a hashed one, like so:</p>
  
  <h2>Hashing</h2>
  
  <pre><code>import bcrypt
  password = b"somepassword"
  hashed = bcrypt.hashpw(password, bcrypt.gensalt())
  </code></pre>
  
  <p>Ok, so far so good.  The given password is now hashed using bcrypt, so it is a string of hashed bytes.</p>
  
  <p><br /></p>
  
  <h2>Verifying</h2>
  
  <p>Now, here's the part that confuses me: to check that a plaintext password matches a hashed password, the <em>same</em> function is used, using the hashed password as a salt:</p>
  
  <pre><code>if bcrypt.hashpw(password, hashed) == hashed:
      print("It Matches!")
  else:
      print("It Does not Match :(")
  </code></pre>
  
  <p><br /></p>
  
  <h2>What's happening?</h2>
  
  <p>Shouldn't the results of both <code>bcrypt.hashpw</code> calls be different, since the input salts are different?  </p>
  
  <p>The only reasonable answer I can think of is that the salt is truncated to a fixed length before being prepended to the hashed password.  That way, when using the result of the hash, only the generated salt is left (after stripping off the trailing hashed password), and the result of hashing the password with the truncated salt is the same as the original.  I don't have any evidence to support this, though.</p>
  
  <p>Why does this work? </p>