我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用bcrypt.checkpw()。
def signin(self, postData): errors = [] response = {} user = self.filter(email = postData['email']) if not user: response['status'] = False errors.append('User not found') else: if bcrypt.checkpw(postData['password'].encode('utf-8'), user[0].password.encode('utf-8')): response['user_id'] = user[0].id response['status'] = True else: errors.append('Invalid email/password') if errors: response['status'] = False response['errors'] = errors return response
def get(cls, db, graph_hash, password, force=False): if len(graph_hash) < 7: return None graph_hash = graph_hash + '_' * (40 - len(graph_hash)) result = db.execute('''select id, graph, view_pass, delete_pass, hash from polycules where hash like ?''', [graph_hash]) graph = result.fetchall() if len(graph) != 1: return None graph = graph[0] polycule = Polycule( db=db, id=graph[0], graph=graph[1], view_pass=graph[2], edit_pass=graph[3], graph_hash=graph[4]) if not force and ( polycule.view_pass is not None and not bcrypt.checkpw(password.encode('utf-8'), polycule.view_pass.encode('utf-8'))): raise Polycule.PermissionDenied return polycule
def login(): form = ctforge.forms.LoginForm() if request.method == 'POST': if form.validate_on_submit(): user = User.get(form.mail.data) if user is not None and bcrypt.checkpw(form.password.data, user.password): if login_user(user): return redirect(url_for('index')) else: flash('Could not log in', 'error') flash('Invalid mail or password', 'error') return redirect(url_for('login')) else: flash_errors(form) return render_template('login.html', form=form)
def login(): error = None if 'name' in session: #check if usr is already logged in return redirect('/') if request.method == 'POST': u = User() u.name = request.form['username'].lower() u = get_user(u) if u is None: error = 'User does not exist!' return render_template('login.html', error=error, user=get_user_by_name(session.get('name'))) #if u.password != request.form['password']: # bcrypt.checkpy(plaintxt, hash) if not bcrypt.checkpw(request.form['password'], u.password): error = 'Wrong password!' return render_template('login.html', error=error, user=get_user_by_name(session.get('name'))) session['name'] = u.name return redirect('/') return render_template('login.html', error=error, user=get_user_by_name(session.get('name')))
def update_unicode_password(userid, password, password_confirm): if password != password_confirm: raise WeasylError('passwordMismatch') if not password_secure(password): raise WeasylError('passwordInsecure') hashpw = d.engine.scalar(""" SELECT hashsum FROM authbcrypt WHERE userid = %(userid)s """, userid=userid).encode('utf-8') if bcrypt.checkpw(password.encode('utf-8'), hashpw): return if not bcrypt.checkpw(d.plaintext(password).encode('utf-8'), hashpw): raise WeasylError('passwordIncorrect') d.engine.execute(""" UPDATE authbcrypt SET hashsum = %(hashsum)s WHERE userid = %(userid)s """, userid=userid, hashsum=passhash(password))
def test_verify_success_if_correct_information_supplied(): # Subtests: # a) Verify 'authbcrypt' table has new hash # b) Verify 'forgotpassword' row is removed. # > Requirement: Get token set from request() user_id = db_utils.create_user(email_addr=email_addr, username=user_name) password = '01234567890123' form_for_request = Bag(email=email_addr, username=user_name, day=arrow.now().day, month=arrow.now().month, year=arrow.now().year) resetpassword.request(form_for_request) pw_reset_token = d.engine.scalar("SELECT token FROM forgotpassword WHERE userid = %(id)s", id=user_id) # Force update link_time (required) resetpassword.prepare(pw_reset_token) form = Bag(email=email_addr, username=user_name, day=arrow.now().day, month=arrow.now().month, year=arrow.now().year, token=pw_reset_token, password=password, passcheck=password) resetpassword.reset(form) # 'forgotpassword' row should not exist after a successful reset row_does_not_exist = d.engine.execute("SELECT token FROM forgotpassword WHERE userid = %(id)s", id=user_id) assert row_does_not_exist.first() is None bcrypt_hash = d.engine.scalar("SELECT hashsum FROM authbcrypt WHERE userid = %(id)s", id=user_id) assert bcrypt.checkpw(password.encode('utf-8'), bcrypt_hash.encode('utf-8'))
def does_authenticate(self, password): """ If the given password matches the hashed password in the database, returns True. Otherwise, returns False. If the hashed password isn't stored as utf-8, it will be updated to the newer utf-8 format while the plaintext password is available. """ expected_hash = self.hashsum.encode('ascii') if bcrypt.checkpw(password.encode('utf-8'), expected_hash): return True elif bcrypt.checkpw(plaintext(password).encode('utf-8'), expected_hash): log.debug('updated old non-ASCII password for userid %d', self.userid) self.set_password(password) return True else: return False
def checkpw(self, pwhash): '''Compare self.password with pwhash. Try to be resistant to timing attacks.''' if 'checkpw' in dir(bcrypt): return bcrypt.checkpw(self.password, pwhash) else: ret = bcrypt.hashpw(self.password, pwhash) return ret == pwhash
def auth_with_cache(self, unreach=False): key = self.username + ':' + self.domain if key in self.ctx.cache_db: now = self.now (pwhash, ts1, tsv, tsa, rest) = self.ctx.cache_db[key].split("\t", 4) if ((int(tsa) + self.ctx.ttls['query'] > now and int(tsv) + self.ctx.ttls['verify'] > now) or (unreach and int(tsv) + self.ctx.ttls['unreach'] > now)): if self.checkpw(pwhash): self.ctx.cache_db[key] = "\t".join((pwhash, ts1, tsv, str(now), rest)) self.try_db_sync() return True return False
def check_password(self, password): print(self.password) return bcrypt.checkpw(password.encode('utf-8'), self.password.encode('utf-8'))
def verify_user(self, email: str, password: str): """ Verify user on login. Raises ------ NoUserError Raised when user's email-id does not exist. Returns ------- bool Whether verification succeeded or failed. """ if len(password) < 8 or len(password) > 72: raise LengthError("password", "Password length should be between 8 and 72 characters.") if not self._is_valid_email(email): raise ValidationError("Please enter a valid email-id.") with self.conn: with self.conn.cursor() as cur: cur.execute( """ SELECT user_password_hash FROM users WHERE user_email = %s """, (email, ) ) results = cur.fetchall() if len(results) == 0: raise NoUserError("User does not exist. Do you want to register a new account?") return bcrypt.checkpw(password.encode("utf-8"), results[0][0].encode("utf-8")) # This is used with myInfo api endpoint
def is_valid_password(self, password): """ Ensure that the provided password is valid. We are using this instead of a ``sqlalchemy.types.TypeDecorator`` (which would let us write ``User.password == password`` and have the incoming ``password`` be automatically hashed in a SQLAlchemy query) because ``compare_digest`` properly compares **all*** the characters of the hash even when they do not match in order to avoid timing oracle side-channel attacks. :param str password: Password to compare to Login's hash :return bool: Password matches """ return bcrypt.checkpw(password.encode('utf8'), self._password)
def can_save(self, edit_pass): if not bcrypt.checkpw(edit_pass.encode('utf-8'), self.edit_pass.encode('utf-8')): raise Polycule.PermissionDenied
def delete(self, password, force=False): if not force and not bcrypt.checkpw(password.encode('utf-8'), self.edit_pass.encode('utf-8')): raise Polycule.PermissionDenied cur = self._db.cursor() cur.execute('delete from polycules where id = ?', [self.id]) self._db.commit()
def check_password(self, value): return bcrypt.checkpw(value.encode('utf-8'), self.password.encode('utf-8'))
def authenticate_user(username,password): entry = get_user_entry(username) if entry : server_hash = entry.password if bcrypt.checkpw(password,server_hash): return "Login successful",200 else: return "Login Credential didn't match",412 else: return "User Entry not found",412
def checkpw(password, hashed): digest = hashlib.sha256(password.encode()).digest() encoded = base64.b64encode(digest) if sys.version_info >= (3, 0): return bcrypt.checkpw(encoded, hashed) else: return bcrypt.checkpw(encoded, hashed.encode())
def post(self): username = self.get_body_argument("username") password = self.get_body_argument("password").encode('utf8') admin_password = config.Get("admin_password").encode('utf8') if username == config.Get("admin_username") and bcrypt.checkpw(password, admin_password): self.set_secure_cookie("i", token_urlsafe(32)) self.redirect("/admin") else: self.redirect("/login")
def log_user_in(): """Logs user into account based on form input.""" # get user input email = request.form.get("email") form_password = request.form.get("password") # check database for user existing_user = User.query.filter(User.email == email).first() user_id = existing_user.user_id if not existing_user: flash("You must create an account first") return redirect("/") else: # check password accuracy user_password = existing_user.password if not bcrypt.checkpw(form_password.encode("utf8"), user_password.encode("utf8")): flash("The password you entered does not match your account") return redirect("/") else: # take user to profile only if password matches database session["user_id"] = user_id flash("You've successfully logged in") return redirect("/profile/{}".format(user_id))
def valid(self,plain_password,enc_password): return bcrypt.checkpw(plain_password.encode('utf-8'), enc_password.encode('utf-8'))
def compare_crypt(plainhash, plaintext): hash = plainhash.encode('ascii') text = plaintext.encode('ascii') return bcrypt.checkpw(text, hash) # Return true if password and username match, otherwise false
def login(): session = request.environ.get('beaker.session') ip = ip_check(session) ban = ban_check(ip) if(request.method == 'POST'): if(ban == 1): return redirect('/ban') else: db_ex("select * from user where id = '" + db_pas(request.forms.id) + "'") user = db_get() if(user): if(session.get('Now') == True): return redirect('/error/11') elif(bcrypt.checkpw(bytes(request.forms.pw, 'utf-8'), bytes(user[0]['pw'], 'utf-8'))): session['Now'] = True session['DREAMER'] = request.forms.id db_ex("select * from custom where user = '" + db_pas(request.forms.id) + "'") css_data = db_get() if(css_data): session['Daydream'] = css_data[0]['css'] else: session['Daydream'] = '' db_ex("insert into login (user, ip, today) value ('" + db_pas(request.forms.id) + "', '" + db_pas(ip) + "', '" + db_pas(get_time()) + "')") db_com() return redirect('/user') else: return redirect('/error/13') else: return redirect('/error/12') else: if(ban == 1): return redirect('/ban') else: if(session.get('Now') == True): return redirect('/error/11') else: return template('index', custom = custom_css_user(session), license = set_data['license'], login = login_check(session), title = '???', enter = '???', logo = set_data['name'], tn = 15)
def change_password(): session = request.environ.get('beaker.session') ip = ip_check(session) ban = ban_check(ip) if(request.method == 'POST'): if(request.forms.pw2 == request.forms.pw3): if(ban == 1): return redirect('/ban') else: db_ex("select * from user where id = '" + db_pas(request.forms.id) + "'") user = db_get() if(user): if(session.get('Now') == True): return redirect('/logout') elif(bcrypt.checkpw(bytes(request.forms.pw, 'utf-8'), bytes(user[0]['pw'], 'utf-8'))): hashed = bcrypt.hashpw(bytes(request.forms.pw2, 'utf-8'), bcrypt.gensalt()) db_ex("update user set pw = '" + db_pas(hashed.decode()) + "' where id = '" + db_pas(request.forms.id) + "'") db_com() return redirect('/login') else: return redirect('/error/10') else: return redirect('/error/9') else: return redirect('/error/20') else: if(ban == 1): return redirect('/ban') else: if(session.get('Now') == True): return redirect('/logout') else: return template('index', custom = custom_css_user(session), license = set_data['license'], login = login_check(session), title = '???? ??', enter = '??', logo = set_data['name'], tn = 15)
def check_user_password(user_info): try: return_msg = {} if user_info['user_name'] == "": return_msg['fail'] = 'Wrong user name' return return_msg with UserDao() as userDao: password = userDao.getUserPassword(userName=user_info['user_name']) if password == None: return_msg['fail'] = 'No such user' return return_msg hashed_passwd = password.encode('utf-8') if bcrypt.checkpw(user_info['user_password'].encode('utf-8'),hashed_passwd): return_msg['success'] = 'Hello {user_name}'.format(user_name=user_info['user_name']) else: return_msg['fail'] = 'Wrong password' return return_msg except DB_Exception as e: return_msg['fail'] = 'DB Exception' return_msg["error"] = e.args[1] return return_msg except Exception as e: return_msg['fail'] = str(e) return return_msg
def change_password(json_obj): try: return_msg = {} return_msg["result"] = "fail" try: user_name = json_obj["user_name"].decode('utf-8') old_password = json_obj["old_password"] new_password = json_obj["new_password"] except: return_msg["error"] = "input parameter missing" return return_msg user_id = get_user_id(user_name) if isinstance(user_id,dict): return_msg["error"] = "no such user name" return return_msg with UserDao() as userDao: password = userDao.getUserPassword(userId=user_id) try: hashed_key = password.encode('utf-8') if bcrypt.checkpw(old_password.encode('utf-8'),hashed_key): hashed_key = bcrypt.hashpw(new_password.encode('utf-8'),bcrypt.gensalt()) with UserDao() as userDao: userDao.updatePassword(hashed_key.decode('utf-8'),userId=user_id) else: return_msg["error"] = "old password incorrect" return return_msg except Exception as e: return_msg["error"] = str(e) return return_msg return_msg["result"] = "success" return return_msg except DB_Exception as e: return_msg["error"] = e.args[1] return return_msg
def checkpassword(self, password, hashedpw): if bcrypt.checkpw(password.encode('utf-8'), hashedpw.encode('utf-8')): return True else: return False
def check_password(self, pw): if self.password_hash is not None: expected_hash = self.password_hash.encode('utf8') return bcrypt.checkpw(pw.encode('utf8'), expected_hash) return False
def validate_password(username, pw): hashed_pw = get_hashed_pw(username) if not hashed_pw: return False expected_hash = hashed_pw.encode('utf8') return bcrypt.checkpw(pw.encode('utf8'), expected_hash)
def check_password(pw, hashed_pw): expected_hash = hashed_pw.encode('utf8') return bcrypt.checkpw(pw.encode('utf8'), expected_hash)
def check_password(self, password): return bcrypt.checkpw(password.encode('utf-8'), self.pw_hash.encode('utf-8'))
def post(self): # Get username and password from request username = self.get_argument('username', '') password = self.get_argument('password', '') if username != 'admin' and password != 'admin': try: session = self.acquire_sql_session() except: raise HTTPError(500, 'Could not acquire session for database') try: query = session.query(Admin.password) \ .filter(Admin.username == username) result = session.execute(query) except: raise HTTPError(500, 'Database error') db_pass = None for pwd in result: db_pass = pwd if not db_pass: self.render("login.html", invalid=True) if bcrypt.checkpw(password.encode('utf8'), db_pass[0].encode('utf8')): self.set_secure_cookie("admin", username) self.get_current_user() self.redirect(r"/") self.render("login.html", invalid=True) session.close() else: self.set_secure_cookie("admin", "admin") self.redirect(r"/")
def check_password(self, pw): return bcrypt.checkpw(pw.encode("utf-8"), self.password.encode("utf-8"))
def check_password_match(moderator: ModeratorModel, password: str): if not validation.check_password_validity(password): raise ArgumentError(MESSAGE_INVALID_PASSWORD) with session() as s: moderator_orm_model = s.query(ModeratorOrmModel).filter_by(id=moderator.id).one() moderator_hashed_password = moderator_orm_model.password s.commit() if not bcrypt.checkpw(password.encode(), moderator_hashed_password): raise ArgumentError(MESSAGE_PASSWORD_INCORRECT)
def authAdmin(message, sock): # simple authentication of the admin connection msg = message.split() user = msg[1] pwd = msg[2] c = conUsers.cursor() c.execute("SELECT userID, passHash, isAdmin, isBanned, MFAEnabled, token FROM users WHERE userID=?", (user,)) result = c.fetchone() uid, hash, isAdmin, isBanned, MFA, tokenMFA = result if len(result) == 0: tx = "Authentication Error, Please Retry Connection" return tx if isAdmin: # checks if this user is allowed to be a sysadmin. if (sock.remote_address[0] == '127.0.0.1') or baseConfig.getboolean("Network Configuration", "Allow Remote Administration"): if bcrypt.checkpw(pwd.encode("utf8"), hash): global sockAdmin; sockAdmin = sock tx = b"202" # 202 "Request Accepted" indicates successful Auth. systemLogger.info("%s authed as admin from %s" % (user, sock.remote_address[0])) return tx else: tx = "Authentication Error, Please Retry Connection" return tx else: tx = "Remote administration is not enabled on this server" return tx
def test_store_recovery_codes(): user_id = db_utils.create_user() valid_code_string = "01234567890123456789,02234567890123456789,03234567890123456789,04234567890123456789,05234567890123456789,06234567890123456789,07234567890123456789,08234567890123456789,09234567890123456789,10234567890123456789" _insert_recovery_code(user_id) # store_recovery_codes() will not accept a string of codes where the total code count is not 10 invalid_codes = valid_code_string.split(',').pop() assert not tfa.store_recovery_codes(user_id, ','.join(invalid_codes)) # store_recovery_codes() will not accept a string of codes when the code length is not tfa.LENGTH_RECOVERY_CODE invalid_codes = "01,02,03,04,05,06,07,08,09,10" assert not tfa.store_recovery_codes(user_id, invalid_codes) # When a correct code list is provided, the codes will be stored successfully in the database assert tfa.store_recovery_codes(user_id, valid_code_string) # Extract the current hashed recovery codes query = d.engine.execute(""" SELECT recovery_code_hash FROM twofa_recovery_codes WHERE userid = %(userid)s """, userid=user_id).fetchall() # Ensure that the recovery codes can be hashed to the corresponding bcrypt hash valid_code_list = valid_code_string.split(',') for row in query: code_status = False for code in valid_code_list: if bcrypt.checkpw(code.encode('utf-8'), row['recovery_code_hash'].encode('utf-8')): # If the code matches the hash, then the recovery code stored successfully code_status = True break # The code must be valid assert code_status
def is_recovery_code_valid(userid, tfa_code, consume_recovery_code=True): """ Checks the recovery code table for a valid recovery code. Determine if a supplied recovery code is present in the recovery code table for a specified userid. If present, consume the code by deleting the record. Case-insensitive, as the code is converted to upper-case before querying the database. Parameters: userid: The userid of the requesting user. tfa_code: A candidate recovery code to check. consume_recovery_code: If set to True, the recovery code is consumed if it is valid, otherwise the call to this function is treated as a query to the validity of the recovery code. (Default: Boolean True) Returns: Boolean True if the code was valid and has been consumed, Boolean False, otherwise. """ # Recovery codes must be LENGTH_RECOVERY_CODE characters; fast-fail if this is not the case if len(tfa_code) != LENGTH_RECOVERY_CODE: return False # First extract the bcrypt hashes. recovery_code_hash_query = d.engine.execute(""" SELECT recovery_code_hash FROM twofa_recovery_codes WHERE userid = %(userid)s """, userid=userid).fetchall() # Then attempt to hash the input code versus the stored code(s). for row in recovery_code_hash_query: if bcrypt.checkpw(tfa_code.upper().encode('utf-8'), row['recovery_code_hash'].encode('utf-8')): # We have a match! If we are deleting the code, do it now. if consume_recovery_code: d.engine.execute(""" DELETE FROM twofa_recovery_codes WHERE userid = %(userid)s AND recovery_code_hash = %(recovery_code_hash)s """, userid=userid, recovery_code_hash=row['recovery_code_hash']) # After deletion--if applicable--return that we succeeded. return True # If we get here, ``tfa_code`` did not match any stored codes. Return that we failed. return False
def check_user(self, username, password): result = await self.db.find_one({'user': username}, projection={ 'password': True, '_id': True }) if result is None: raise InvalidRequest('User does not exist') password = password.encode('utf-8') if not bcrypt.checkpw(password, result['password']): raise InvalidRequest('Wrong password') return str(result['_id'])
def selfmanagement(): if request.method == 'POST': u = get_user_by_name(session.get('name')) if not bcrypt.checkpw(request.form['password_old'], u.password): success = "Passwort falsch!" else: if len(request.form['password1']) > 0: if ('password1' in request.form) & ('password2' in request.form): if (request.form['password1'] == request.form['password2']): u.password = bcrypt.hashpw(request.form['password1'], bcrypt.gensalt()) u.rfid_id = request.form['rfid_id'] if 'onlyrfid' in request.form: u.onlyrfid = True else: u.onlyrfid = False update_user(u) success = u'Einstellungen wurden übernommen!' else: success = u'Neue Passwörter stimmen nicht überein!' else: u.rfid_id = request.form['rfid_id'] if 'onlyrfid' in request.form: u.onlyrfid = True else: u.onlyrfid = False update_user(u) success = u'Einstellungen wurden übernommen!' return render_template('selfmanagement.html', success=success, user=get_user_by_name(session.get('name'))) if request.method == 'GET': return render_template('selfmanagement.html', user=get_user_by_name(session.get('name'))) #migrate the db to hashed passwords #@app.route('/hashdb') #@requires_baron #def hashdb(): # users = get_users() # for user in users: # user.password = bcrypt.hashpw(user.password, bcrypt.gensalt()) # update_user(user) # return render_template('index.html', users=users, user=get_user_by_name(session.get('name')))
def taskSys(message, requester): msg = message contents = msg.split(" ") operation = contents[0].lower() session = requester if operation == "register": # expects "register user pass" userLogger.info("%s is requesting to add user %s to the game." % (session.remote_address[0], contents[1])) if extantUser(contents[1]): # Prevent overwrite of existing user entries userLogger.info("Request cannot be completed - existing user.") tx = "This user already exists. Please change usernames and try again." return tx else: # The user doesn't exist so let's add it salted = bcrypt.hashpw(contents[2].encode('utf8'), bcrypt.gensalt()) salted = str(salted) # The next several lines are necessary or the salt/pw store is broken when read from config strip1 = salted.lstrip("b'") strip2 = strip1.rstrip("'") salted = strip2 addargs = ([ contents[1].lower(), salted, False, False, False, False, False ]) conUsers.execute('INSERT INTO users VALUES (?,?,?,?,?,?,?)', addargs) conUsers.commit() tx = "Your registration was successful. Please record your password for future reference." return tx elif operation == "login": # expects "login user pass" userLogger.info("%s is attempting to log in as %s" % (session.remote_address[0], contents[1])) fooargs = (contents[1].lower()) curse = conUsers.cursor() curse.execute('SELECT userID, passHash, isAdmin, isBanned, banExpy, MFAEnabled, token FROM users WHERE userID=?', (fooargs,)) record = curse.fetchall() if len(record) == 0: tx = "Login Failed" return tx uid, hash, admin, banned, expyBan, MFA, tokenMFA = record[0] if banned: now = datetime.datetime.now().timestamp() if expyBan >= now: conUsers.execute('UPDATE users SET banned=False WHERE userID=?', uid) else: tx = "Login Failed" return tx authed = False # You must always start with the decision that Alice is actually Mallory authed = bcrypt.checkpw(contents[2].encode('utf8'), hash.encode('utf8')) if authed: sessions.update(dict({session:contents[1]})) positions.update(dict({session:logroom})) welcome = str("You are now known as %s." % contents[1]) tx = welcome userLogger.info("They were successful") return tx else: tx = "Login Failed" #Purposefully vague status return tx elif operation == "quit": tgt = sessions[session] del sessions[session] print("%s has quit" % tgt) tx = b"200" # 200 closes connection "at client request". return tx