def validate(username, password_hash): Global.cursor.execute( "SELECT username, salt, hash FROM Account WHERE username = %s;", (username,) ) result = Global.cursor.fetchall() if len(result) > 0: salt_method_auto_read = Global.config.getboolean("miscellaneous", "salt_method_auto_read") salt_method = None if not salt_method_auto_read: salt_method = Global.config.get("miscellaneous", "salt_method") for db_username, db_salt, db_hash in result: if db_username == username: sha_function = Global.config.get("miscellaneous", "sha_function") if salt_method_auto_read: salt_method = ("argon2" if db_hash.startswith("$argon2") else sha_function) if salt_method.upper().startswith("SHA"): if sha_function.upper().startswith("SHA3"): hash_function = getattr(hashlib, sha_function.lower().replace("-", "_")) else: hash_function = getattr(hashlib, sha_function.lower().replace("-", "")) if db_hash == hash_function(password_hash.encode(Global.encoding) + db_salt.encode(Global.encoding)).hexdigest(): return True elif salt_method.lower() == "argon2": try: argon2.verify_password( db_hash.encode(Global.encoding), password_hash.encode(Global.encoding), type=Type.ID ) except argon2.exceptions.VerificationError: continue return True else: logging.critical("Salt method is invalid.") raise Exception logging.info("\"" + username + "\" tried logging in with wrong password") else: logging.info("user \"" + username + "\" not found") return False
def test_wrong_arg_type(self): """ Passing an argument of wrong type raises TypeError. """ with pytest.raises(TypeError): verify_password(TEST_HASH_I, TEST_PASSWORD.decode("ascii"))
def test_fail_wrong_argon2_type(self): """ Given a valid hash and password and wrong type, we fail. """ with pytest.raises(VerificationError): verify_password(TEST_HASH_I, TEST_PASSWORD, Type.D)
def test_success(self, type, hash): """ Given a valid hash and password and correct type, we succeed. """ assert True is verify_password(hash, TEST_PASSWORD, type)
def check_password(self, passwd): try: return argon2.verify_password(self.passwd, bytes(passwd, "UTF-8")) except argon2.exceptions.VerifyMismatchError: return False