Search code examples
pythonhashpasswordsaccount

Hashing Password in .py file


how i said in the title, i want the password to be hashed when is saved. Its possible with this?

    def __OnClickSaveLoginButton(self):
    id = self.idEditLine.GetText()
    pwd = self.pwdEditLine.GetText()
    if (len(id) == 0 or len(pwd) == 0):
        self.PopupNotifyMessage("ID and Password required",self.SetIDEditLineFocus)
        return
    file_object  = open("account.cfg", "w")
    file_object.write(id+"\n"+pwd)
    self.PopupNotifyMessage("Saved.",self.SetIDEditLineFocus)
    file_object.close()

Solution

  • You'll want to use the python hashlib. An example could look something like this:

      import hashlib
    
      def valid_password(userid, password):
          user = get_user(userid)
          pw_hash = hashlib.sha256(password).hexdigest()
          if user.hash == pw_hash:
              return True
          return False
    

    Also I recommend reviewing some password storage best practices noted in this SO

    Edit: I used sh256 in this example, but that is more useful as a message digest. A better use would be hashlib.pbkdf2_hmac or another key derivation function. There is a good write up here.