title: How to retrieve passwords from a database
body: <p>I am building a registration system for my web application wherein users provide a username and a password. This data is stored in a <code>postgresql</code> database. I am using bcrypt to generate a salted hash of the user entered password as follows</p>
  
  <pre><code>import bcrypt
  hashed = bcrypt.hashpw(PasswordFromWebForm.encode('UTF-8'), bcrypt.gensalt()) 
  </code></pre>
  
  <p>This creates a salted password that looks something like this - <code>b'$2b$12$GskbcRCMFHGuXumrNt3FLO'</code></p>
  
  <p>I am storing this value in a <code>postgresql</code> database. Next, when a user tries to login to the system, I want to verify his/her credentials. To do this, I intend to do something along the lines of - </p>
  
  <pre><code>import psycopg2
  conn = psycopg2.connect("dbname=test user=me")
  cur = conn.cursor()
  
  saltedpassword = cur.execute("SELECT saltedpassword FROM test WHERE loginid = %s", (LoginIDFromWebForm,))
  
  if bcrypt.hashpw(PasswordFromWebForm.encode('UTF-8'), saltedpassword) == saltedpassword:
      print("Success")
  </code></pre>
  
  <p>This does not work. It throws the following <code>TypeError: Unicode-objects must be encoded before hashing</code> error. </p>
  
  <p>I suspect that this error is because the variable <code>saltedpassword</code> stores the value as a string like this <code>"b'$2b$12$GskbcRCMFHGuXumrNt3FLO'"</code> instead of just plain <code>b'$2b$12$GskbcRCMFHGuXumrNt3FLO'</code> (Notice the quotes enclosing the salted password in the former)</p>
  
  <p>How do I get around this problem? What is the best way to store the salted hashed password in a database and how do I go about retrieving it when needed for verification? Apologies for the rather longish question  - please help. </p>