def check(self, password: str) -> bool: """ Checks the given password with the one stored in the database """ return ( pbkdf2_sha512.verify(password, self.password) or pbkdf2_sha512.verify(password, pbkdf2_sha512.encrypt(self.api_key)) )
def check_password(self, password): stored_hash = self['pwhash'] if pbkdf2_sha512.verify(password, stored_hash): return True else: return False
def test_upgrade_from_pbkdf2_with_less_rounds(self): '''set up a pbkdf key with less than the default rounds If the number of default_rounds is increased in a later version of passlib, ckan should upgrade the password hashes for people without involvement from users''' user = factories.User() password = u'testpassword' user_obj = model.User.by_name(user['name']) # setup hash with salt/rounds less than the default old_hash = pbkdf2_sha512.encrypt(password, salt_size=2, rounds=10) user_obj._password = old_hash user_obj.save() nt.assert_true(user_obj.validate_password(password.encode('utf-8'))) # check that the hash has been updated nt.assert_not_equals(old_hash, user_obj.password) new_hash = pbkdf2_sha512.from_string(user_obj.password) nt.assert_true(pbkdf2_sha512.default_rounds > 10) nt.assert_equals(pbkdf2_sha512.default_rounds, new_hash.rounds) nt.assert_true(pbkdf2_sha512.default_salt_size, 2) nt.assert_equals(pbkdf2_sha512.default_salt_size, len(new_hash.salt)) nt.assert_true(pbkdf2_sha512.verify(password, user_obj.password))
def _verify_and_upgrade_pbkdf2(self, password): if pbkdf2_sha512.verify(password, self.password): self._set_password(password) self.save() return True else: return False
def check_hashed_password(password, hashed_password): ''' Checks that the password the user sent (password) matches that of the database (hashed_password or user_data['password'] The database password is encrypted more than the user's password at this stage :param password:sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: True if passwords match, False otherwise ''' return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ :param password: sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted :return: """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks that password sent by user matches the password in the database. The database password is encrypted :param password: sha512 password :param hashed_password: pbkdf2_sha512 password :return: True id password match, False otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks that the password the user sent matches that of the database. The database password is encrypted more than the user's password at this stage. :param password: sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted password (slightly slower than the simple sha512, which is just a hash and not encryption) :return: True if passwords match, False otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def validate(cls, username_or_email, password): u = cls.query.filter( db.or_(cls.username == username_or_email, cls.email == username_or_email) ).one_or_none() if not u: raise RuntimeError("Invalid username/email or password.") if not pbkdf2_sha512.verify(password, u.password_hash): raise RuntimeError("Invalid username/email or password.") return u
def check_hashed_password(password, hashed_password): """ Checks that the password that the user sent matches that of the database. The database password is encrypted more than the user's password at this stage :param hashed_password: :return: """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks that the password the user sent matches what is in the database. The password in the database is encrypted. :param password: sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: True is passwords match, False otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def test_upgrade_from_sha_with_unicode_password(self): user = factories.User() password = u'testpassword\xc2\xa0' user_obj = model.User.by_name(user['name']) # setup our user with an old password hash old_hash = self._set_password(password) user_obj._password = old_hash user_obj.save() nt.assert_true(user_obj.validate_password(password)) nt.assert_not_equals(old_hash, user_obj.password) nt.assert_true(pbkdf2_sha512.identify(user_obj.password)) nt.assert_true(pbkdf2_sha512.verify(password, user_obj.password)) # check that we now allow unicode characters nt.assert_false(pbkdf2_sha512.verify('testpassword', user_obj.password))
def check_hashed_password(password, hashed_password): """ Checks the password user sent matches with the password stored in database The database password is encrypted more than the one user sent :param password: sha512 hashed :param hashed_password: pbkdf2_sha512 encrypted password :return: Boolean value """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks that the password the user sent matches the one hashed in the database :param password: SHA512 hashed password from front end :param hashed_password: the PBKDF2 encrypted password in the database for the user :return: True if password match, false otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ check that password of user sent mathces that of the database the database password is encrypted more thn the user password at this stage :param password: sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: True if passwords match, False otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ checks that the password the user sent matches with the one in db the database password is encrypted more than the user's password at this point :param password: sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: True if password match """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ checks that the password user sent matches the database The database password is encrypted more than user's at this point :param password: sha512-hashed password :param hashed_password: pbkf2_sha512 password :return: True if passwords match otherwise False """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks that the password the user sent matches that of the database. The database password is encrypted more than the user's password at this stage. :param password: sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: True if passwords match, False otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Check thats the PW user send matches the one in the database DB PW is encrypted more than the user's password at this stage :param password: :param hashed_password: pbkdf2_sha512 encrypted PW :return: True (PW match), False otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks the password the user sent matches tha password stored in the database The password is encrypted more than the user's password at this stage :param password: sha-512 hashed password :param hashed_password: pbkdf2_sh512 encrypted passsword :return: True if password matches false otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks that the password the user sent matches that of the database password The database password is encrypted more than the user's password at this stage. :param password: sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: True if passwords match, False otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks that the password users send matches the database password. THe database password is encrypted more than the users's password at this stage. :param password: shah512 hashed password :param hashed_password: pbkdf2-sha512 encrypted password :return: TRue is password match, false otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def verify(cleartext, ciphertext): """ Match cleartext against a hash :param cleartext: :param ciphertext: :return: """ return pb.verify(cleartext, ciphertext)
def invalid_credentials(form,field): username_entered = form.username.data password_entered = field.data user_object = User.query.filter_by(username = username_entered).first() if user_object is None: raise ValidationError("Username/Password incorrect.") elif not pbkdf2_sha512.verify(password_entered,user_object.password): raise ValidationError("Username/Password incorrect.")
def check_hashed_password(password, hashed_password): """ Checks the password the user entered matches with that of the database The database password is encrypted more than the user password at this stage :param password: sha512 hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: True if password match, false otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def check_hashed_password(password, hashed_password): """ Checks that the user sent pass matches the database version :param password: sha512 hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: true if pass match, false otherwise """ return pbkdf2_sha512.verify(password, hashed_password)
def verify_password(self, password_attempt): """Verifies that the input password matches with the stored password. Args: password_attempt(str): The input password. Returns: True if the passwords match, False if not. """ return pbkdf2_sha512.verify(password_attempt, self._password)
def verify_password(self, password_attempt): """Verifies that the input password matches with the stored password. Args: password_attempt(str): The input password. Returns: (bool): True if the passwords match, False if not. """ return pbkdf2_sha512.verify(password_attempt, self._password)
def checkPassword(email, password): conn = db.get_db() cur = conn.cursor() cur.execute("SELECT PasswordHash FROM Registrants WHERE Email = (?);", (email, )) #get hash from tuple storedHash = cur.fetchone()[0] db.close_db() #check if hashes match return passHash.verify(password, storedHash)
def check_hashed_password(password, hashed_password): ''' Checks that the password user sent matches the pw in the db The db pw is encrypted more than the user's at this stage :param password: sha512-hashed pw :param hashed_password: pbkdf2_sha512 encrypted :return: true if pws match else false ''' return pbkdf2_sha512.verify(password, hashed_password)
def invalid_credentials(form, field): """ Username and password checker """ username = form.username.data password = field.data user_object = User.query.filter_by(username=username).first() if user_object is None: raise ValidationError("Username does not exist.") elif not pbkdf2_sha512.verify(password, user_object.password): raise ValidationError("Username or Password is incorrect.")
def login(): if request.method == 'POST': if pbkdf2_sha512.verify( request.form['password'], '$pbkdf2-sha512$25000$H6N0LqV0rhXiPOc8R.jduw$3QHAzZkv76ej5bWWzZ9nWH5WmXrttRMwYEmo8xKvIvXHZhWNKVPXpv2JYZqyxSuTdi4DzcSrDbFovQCJZOJyzQ' ): session['login'] = True return redirect('/') else: session['login'] = False return render_template("login.html")
def check_hashed_password(password, hashed_password): ''' Checks that the user sent matches theone in database The database password is encrypted more than the user's password at this stage. :param password: sha512-hashed password :param hashed_password: pbkdf2_sha512 encrypted password :return: True is passwords match, False otherwise ''' return pbkdf2_sha512.verify(password, hashed_password)
def login(username=""): if request.method == 'POST': username = request.form.get('username') user_info = LOGINS.find_one({'username': username}, {'password': 1}) if user_info: hash = user_info.get('password') allow = pbkdf2_sha512.verify(request.form.get('password'), hash) if allow: session.update({'username': username}) return redirect(request.args.get('next') or url_for('index')) return render_template('login.html', username=username)
def post(self, user_id): request.get_json() args = enroll_post_args.parse_args() class_id = int(args['id']) password = str(args['password']) result = database.ClassModel.query.filter_by(id=class_id).first() if not pbkdf2_sha512.verify(password, result.password): abort(204, message='Class password is incorrect') database.db.session.execute(database.userClass.insert().values(class_id=class_id, user_id=user_id)) database.db.session.commit() return 201
def post(self): request.get_json() args = login_parser.parse_args() email = str(args['email']) pwd = str(args['password']) result = database.UserModel.query.filter_by(email=email).first() if not result: return '',204 elif not pbkdf2_sha512.verify(pwd, result.password): return '',204 return result, 201
def check_sha512(unknown_password, valid_password): """Valida un String y un String cifrado. Argumentos: unknown_password - String a comparar valid_password - String cifrado """ if unknown_password is None or valid_password is None: return "Sin parametros" else: return pbkdf2_sha512.verify(unknown_password, valid_password)
def check_hashed_password(password, encrypted_password): """ password (user's password from site), matches database's password version The password that's in database, is actually "encrypted" (with pbf) :param password: sha512-hashed password :param encrypted_password: pbk encrypted password :return: True if passwords match """ return pbkdf2_sha512.verify(password, encrypted_password)
def change_pw(username, password_old, password_new): """Change the user password""" user = user_by_name(username) if pbkdf2_sha512.verify(password_old, user['password']): cursor, conn = db_sql.connect('users.db') sql = ("UPDATE users SET password = ? WHERE username = ?") cursor.execute(sql, (pbkdf2_sha512.encrypt(password_new), username, )) conn.commit() conn.close() return "0" else: return _("Wrong password")
def test_upgrade_from_sha(self): user = factories.User() user_obj = model.User.by_name(user['name']) # setup our user with an old password hash old_hash = self._set_password('testpass') user_obj._password = old_hash user_obj.save() user_obj.validate_password('testpass') nt.assert_not_equals(old_hash, user_obj.password) nt.assert_true(pbkdf2_sha512.identify(user_obj.password)) nt.assert_true(pbkdf2_sha512.verify('testpass', user_obj.password))
def lambda_handler(event, context): details = event['body'] digest = details['digest'] hash_pass = details['hash_pass'] password = details['password'] if digest == "sha256": verification = pbkdf2_sha256.verify(password, hash_pass) elif digest == "sha512": verification = pbkdf2_sha512.verify(password, hash_pass) else: verification = pbkdf2_sha1.verify(password, hash_pass) return verification
def changepwd(): old_pwd, new_pwd, conf_pwd = map(request.form.get, ["old_pwd", "new_pwd", "conf_pwd"]) user = json.load(open("./data/User/" + User.cu() + ".json")) if pbkdf2_sha512.verify(old_pwd, user["password_digest"]): if new_pwd == conf_pwd: user["password_digest"] = pbkdf2_sha512.encrypt(new_pwd) with open("./data/User/" + User.cu() + ".json","w") as outFile: json.dump(user, outFile, indent=4) return "Success" else: return "not_match" else: return "not_auth"
def check_password(self, raw_password): """ Verilen encrypt edilmemiş şifreyle kullanıcıya ait encrypt edilmiş şifreyi karşılaştırır. Args: raw_password (str) Returns: bool: Değerler aynı olması halinde True, değilse False döner. """ return pbkdf2_sha512.verify(raw_password, self.password)
def login(username, password, session_id): """Login""" user = user_by_name(username) if user != None and pbkdf2_sha512.verify(password, user['password']): if session_id != None: cursor, conn = db_sql.connect('users.db') session_ids = [session_id] + user['session_ids'] sql = ("UPDATE users SET session_ids = ? WHERE username = ?") cursor.execute(sql, (session_ids, username, )) conn.commit() conn.close() return True else: return False
def validate_login (self, name, password): with session_scope(self.session) as s: # Find the user with the given name try: u = s.query(User).filter(User.name == name).one() except NoResultFound: raise InvalidLogin() # Check password, throw an exception if invalid if not pbkdf2_sha512.verify( password, u.pwhash ): raise InvalidLogin() # Everything good, now return the user id to the caller return int(u.id)
def login(): ''' Authenticate a user and send them to the URL they requested. ''' username, password, remember = map(request.form.get, ["username", "password", "remember"]) userJson = None for u in os.listdir("./data/User/"): if u.lower() == username.lower() + ".json": userJson = json.load(open("./data/User/" + u)) break if userJson and pbkdf2_sha512.verify(password, userJson["password_digest"]): user = User(userJson) flask_login.login_user(user, remember = remember == "on") nextUrl = str(request.form.get("next","/")) return redirect(nextUrl)
def login(): if request.method == 'GET': return render_template('login.html') else: clid = request.form['clid'] password = request.form['password'] registered_user = \ User.query.filter_by(clid=clid).first() if pbkdf2_sha512.verify(password, registered_user.password.hash) \ or registered_user is None: print registered_user.password.hash login_user(registered_user) json_with_names = check_time() return "Hello, cross-origin-world!" else: flash('Number or Password is invalid', 'error') return render_template('ERROR.html')
def check_token(self, token): try: result = self._coll.find_one( filter={'_id': Binary(uuid.UUID(token['_id']).bytes, STANDARD)}, projection={'_id': 0, 'token': 1, 'user': 1} ) if not result: raise TokenError if not pbkdf2_sha512.verify(token['token'], result['token']): raise TokenError self._coll.update_one( filter={'_id': Binary(uuid.UUID(token['_id']).bytes, STANDARD)}, update={'$set': {'lastused': datetime.datetime.utcnow()}} ) return result['user'] except pymongo.errors.ConnectionFailure as err: raise MongoConnError(err)
def login(): """ Handle user login """ if request.method == 'POST': form = LoginForm(request.form) if form.validate(): user = User.query.filter(User.username==form.identifier.data).first() if not user: user = User.query.filter(User.email==form.identifier.data).first() #TODO Flash message if this fails if user and pbkdf2_sha512.verify(form.password.data, user.password.hash) and login_user(user, remember=form.remember_me.data): user.login() return redirect(url_for('index')) if request.method == 'GET': form = LoginForm() return render_template('login.html', form=form)
def verify_secret(self, secret): u""" Returns True if secret is equal to user's secret. **Example usage** >>> import copy >>> from .models_test import USER_TEST >>> user = copy.copy(USER_TEST) >>> assert(not user.verify_secret(u'bad_secret')) >>> assert(user.verify_secret(u'Secr4taB')) >>> user.hash_secret() >>> assert(not user.verify_secret(u'bad_secret')) >>> assert(user.verify_secret(u'Secr4taB')) """ if self.is_secret_hashed: return pbkdf2_sha512.verify(secret, self.secret) return consteq(secret, self.secret)
def check_session(self, token): request_id = request.environ.get("REQUEST_ID", None) self.log.debug("{0} checking token {1}".format(request_id, token["_id"])) result = self._coll.find_one( filter={"_id": Binary(uuid.UUID(token["_id"]).bytes, STANDARD)}, projection={"_id": 0, "token": 1, "user": 1}, ) if not result: self.log.warning("{0} failed checking token {1}, not found in db".format(request_id, token["_id"])) raise SessionError if not pbkdf2_sha512.verify(token["token"], result["token"]): self.log.warning("{0} failed checking token {1}, token not matching".format(request_id, token["_id"])) raise SessionError self._coll.update_one( filter={"_id": Binary(uuid.UUID(token["_id"]).bytes, STANDARD)}, update={"$set": {"lastused": datetime.datetime.utcnow()}}, ) self.log.debug("{0} success checking token {1}".format(request_id, token["_id"])) return result["user"]
def check_credentials(self, credentials): request_id = request.environ.get('REQUEST_ID', None) self.log.info('{0} validating credentials for user {1}'.format( request_id, credentials['user'])) password = self._coll.find_one( filter={'_id': credentials['user']}, projection={'_id': 0, 'password': 1} ) if not password: self.log.warning('{0} failed validating credentials, user {1} not found'.format( request_id, credentials['user'])) raise AuthenticationError if not pbkdf2_sha512.verify(credentials['password'], password['password']): self.log.warning('{0} failed validating credentials, password wrong for user {1}'.format( request_id, credentials['user'])) raise AuthenticationError self.log.info('{0} success validating credentials for user {1}'.format( request_id, credentials['user'])) return credentials['user']
def local_login(self, username, password): """\ Check whether the specified username/password combination is a valid local login; if so, create a new session for this user. """ db_session = cherrypy.serving.request.db_session user = db_session.query(dao.User).filter_by( user_domain_id=0, user_name=username).one() if user is None: # Attempt to validate against a random password. This helps prevent # timing attacks. expected_password = PBKDF2_INVALID_PASSWORD else: expected_password = user.password_pbkdf2 if not pbkdf2_sha512.verify(password, expected_password): raise LoginDeniedError("Invalid username/password combination.") return self.create_session(user.user_id)
def verify_secret(self, secret): """ Returns True if secret is equal to user's secret. **Example usage** >>> user = User(first_name='D.', last_name='F.', mail='*****@*****.**', secret='Secr4taB', admin_platform=True) >>> user.verify_secret('bad_secret') False >>> user.verify_secret('Secr4taB') True >>> user.hash_secret() >>> user.verify_secret('bad_secret') False >>> user.verify_secret('Secr4taB') True """ if self.is_secret_hashed: return pbkdf2_sha512.verify(secret, self.secret) return consteq(secret, self.secret)
def signin(): if request.method == 'POST': # check auth username = request.form['username'] auth = request.form['auth'] verified = pbkdf2_sha512.verify(auth, app.config['AUTH']) if not verified: abort(501) # generate token payload = { 'iss':request.host, 'iat':int(time.time()), 'exp':time.time() + 86400, } secret = app.config['SECRET'] encoded = jwt.encode(payload, secret, algorithm='HS256') print 'new token:%s'%(encoded) return jsonify(token=encoded) return render_template('signin.html')
def login(): next = request.args.get('next', '/dashboard') from urlparse import urlparse o = urlparse(next) next = o[2] # Only allow relative PATH -- dont arbitrarily redirect to user-submitted URL if 'email' in request.form: sql = "SELECT * FROM Users where Username = ? AND status = 1" curs=app.db.db.cursor(oursql.DictCursor) try: curs.execute(sql, [request.form['email']]) user = curs.fetchone() if user is not None and crypt.verify(request.form['password'], user['Password']): session['uid'] = user['ID'] return redirect(next) else: flash("Invalid user/password") except Exception as e: print str(e) flash("An unexpected error occurred") curs.close() return render_template("login.html", url=request.url)
def passwordChange(request): if(has_permission('root', Donate, request)): permission = 'root' else: permission = 'admin' user = Settings.Session.query(User).filter(User.user == authenticated_userid(request)).scalar() error = None if 'form.submitted' in request.params: if not password_hash.verify(request.params['curpass'], user.password): error = 'Current password is incorrect' if request.params['newpass'] != request.params['repeatnew']: error = 'Passwords do not match' if not error: password = password_hash.encrypt(request.params['newpass'], rounds=16000, salt_size=32) Settings.Session.query(User).filter(User.id == user.id).update({'password': password}) try: Settings.Session.commit() except: Settings.Session.rollback() error = 'There was an error applying changes' path = [{'name': 'Home', 'url': request.route_url('admin')},{'name': 'Account Management', 'url': request.route_url('admin/account')}, {'name': 'Change Password', 'url': request.route_url('admin/password')}] return {'community': Settings.Community, 'path': path, 'permission': permission, 'error': error}
def validate_password(self, password): ''' Check the password against existing credentials. :param password: the password that was provided by the user to try and authenticate. This is the clear text version that we will need to match against the hashed one in the database. :type password: unicode object. :return: Whether the password is valid. :rtype: bool ''' if not password or not self.password: return False if not pbkdf2_sha512.identify(self.password): return self._verify_and_upgrade_from_sha1(password) else: current_hash = pbkdf2_sha512.from_string(self.password) if (current_hash.rounds < pbkdf2_sha512.default_rounds or len(current_hash.salt) < pbkdf2_sha512.default_salt_size): return self._verify_and_upgrade_pbkdf2(password) else: return pbkdf2_sha512.verify(password, self.password)