def post(self): data_dict = json.loads(request.data) user = session.get("user") if not user: return abort(404) update_type = data_dict["type"] if update_type == "profile": userid = user["_id"] twitter = data_dict["twitter"] website = data_dict["website"] return cuser.update_profile_info(session, user, twitter, website) elif update_type == "password": userid = user["_id"] user = db.users.find_one({"email": unicode(user['email'])}) if not user: return {'error': 'user not found'}, 404 current_pwd = data_dict["current_pwd"] new_pwd = data_dict["new_pwd"] pwd_hash = user["password"] if bcrypt.hashpw(current_pwd, pwd_hash) != pwd_hash: return {'error': 'password is invalid'}, 404 else: new_pwd_hash = bcrypt.hashpw(new_pwd, bcrypt.gensalt()) db.users.update( {"_id": ObjectId(userid)}, {"$set": {"password": new_pwd_hash}} ) return 200 return 402
def change_password(): require_current = True error = None form = PasswordResetForm() user = User.objects.filter(username=session.get('username')).first() if not user: abort(404) if request.method == 'POST': if form.validate_on_submit(): if bcrypt.hashpw(form.current_password.data, user.password) == user.password: salt = bcrypt.gensalt() hashed_password = bcrypt.hashpw(form.password.data, salt) user.password = hashed_password user.save() # if user is logged in, log him out if session.get('username'): session.pop('username') return redirect(url_for('user_app.password_reset_complete')) else: error = "Incorrect password" return render_template('user/password_reset.html', form=form, require_current=require_current, error=error )
def _digest(self, alg, password, salt=None): """ Helper method to perform the password digest. :param alg: The hash algorithm to use. :type alg: str - 'sha512' | 'bcrypt' :param password: The password to digest. :type password: str :param salt: The salt to use. In the case of bcrypt, when storing the password, pass None; when testing the password, pass the hashed value. :type salt: None or str :returns: The hashed value as a string. """ cur_config = config.getConfig() if alg == 'sha512': return hashlib.sha512((password + salt).encode('utf8')).hexdigest() elif alg == 'bcrypt': try: import bcrypt except ImportError: raise Exception( 'Bcrypt module is not installed. See girder.local.cfg.') password = password.encode('utf8') if salt is None: rounds = int(cur_config['auth']['bcrypt_rounds']) return bcrypt.hashpw(password, bcrypt.gensalt(rounds)) else: if isinstance(salt, six.text_type): salt = salt.encode('utf8') return bcrypt.hashpw(password, salt) else: raise Exception('Unsupported hash algorithm: %s' % alg)
def create(cls, db, graph, raw_view_pass, raw_edit_pass): if raw_view_pass is not None: view_pass = bcrypt.hashpw( raw_view_pass.encode(), bcrypt.gensalt()).decode() else: view_pass = None if raw_edit_pass is not None: edit_pass = bcrypt.hashpw( raw_edit_pass.encode(), bcrypt.gensalt()).decode() else: edit_pass = None result = db.execute('select count(*) from polycules where graph = ?', [graph]) existing = result.fetchone()[0] if existing != 0: raise Polycule.IdenticalGraph cur = db.cursor() result = cur.execute('''insert into polycules (graph, view_pass, delete_pass, hash) values (?, ?, ?, ?)''', [ graph, view_pass, edit_pass, hashlib.sha1(graph.encode('utf-8')).hexdigest(), ]) db.commit() new_hash = db.execute('select hash from polycules where id = ?', [ result.lastrowid ]).fetchone()[0] return Polycule.get(db, new_hash, None, force=True)
def bcrypt_check_password(raw_pass, stored_hash, extra_salt=None): """ Check to see if this password matches. Args: - raw_pass: user submitted password to check for authenticity. - stored_hash: The hash of the raw password (and possibly extra salt) to check against - extra_salt: (optional) If this password is with stored with a non-database extra salt (probably in the config file) for extra security, factor this into the check. Returns: True or False depending on success. """ if extra_salt: raw_pass = u"%s:%s" % (extra_salt, raw_pass) hashed_pass = bcrypt.hashpw(raw_pass.encode('utf-8'), stored_hash) # Reduce risk of timing attacks by hashing again with a random # number (thx to zooko on this advice, which I hopefully # incorporated right.) # # See also: rand_salt = bcrypt.gensalt(5) randplus_stored_hash = bcrypt.hashpw(stored_hash, rand_salt) randplus_hashed_pass = bcrypt.hashpw(hashed_pass, rand_salt) return randplus_stored_hash == randplus_hashed_pass
def company_login_process(): """Process company login.""" # Get form variables company_email = request.form["company_email"] password = request.form["password"] password_bytes = password.encode('utf-8') hashed = bcrypt.hashpw(password_bytes, bcrypt.gensalt()) company = Company.query.filter_by(company_email=company_email).first() if not company: flash("Incorrect login credentials") return redirect("/company_login") if bcrypt.hashpw(password_bytes, hashed) == hashed: flash("Welcome") else: flash("Incorrect login credentials") return redirect("/company_login") session["company_id"] = company.company_id flash("Logged in") return redirect("/company_profile/%s" % company.company_id)
def test_create_user(): user = model.User() test_username = '******' test_password = '******' test_email = '*****@*****.**' user.create(test_username,test_password,test_email) passwd = user.user.password assert user.user.username == test_username assert bcrypt.hashpw(test_password,passwd) == passwd assert user.user.email == test_email auth_token = hashlib.sha224('%s%s' % (test_username,test_password)) assert user.user.auth_token == auth_token.hexdigest() assert user.get_auth_token() == auth_token.hexdigest() db = MongoModel(project='internal',collection='user') test_result = db.query({'username':test_username}) assert test_result['username'] == test_username assert test_result['email'] == test_email assert bcrypt.hashpw(test_password,test_result['password']) == test_result['password'] assert test_result['auth_token'] == auth_token.hexdigest() db.delete({'username':test_username})
def login_submit(): try: user = dbhandler.col_members.find_one({"username": request.form['username']}) if user['activated'] == False: session['activation_link'] = user['activation_link'] session['activation_email'] = user['email'] return newrender('title_login', '', 'login_err.html', 'login_err_email') if 'migrated' in user: #migrated from koistudy1 if hashlib.md5("request.form['password']").hexdigest() == user['password']: session['username'] = request.form['username'] session['nickname'] = user['nickname'] session['locale'] = user['locale'] log = {"date": datetime.datetime.now(), "type": "login_migrated", "result": "succeed", "username": request.form['username'], "ip": request.remote_addr} user['password'] = bcrypt.hashpw(request.form['password'].encode("UTF-8"), bcrypt.gensalt()) del user['migrated'] dbhandler.col_members.update({'_id': user['_id']}, {"$set": user}, upsert=False) dbhandler.col_logs.insert_one(log) return redirect('/') else: if bcrypt.hashpw(request.form['password'].encode("UTF-8"), user['password'].encode('utf-8')) == user['password']: session['username'] = request.form['username'] session['nickname'] = user['nickname'] session['locale'] = user['locale'] log = {"date": datetime.datetime.now(), "type": "login", "result": "succeed", "username": request.form['username'], "ip": request.remote_addr} dbhandler.col_logs.insert_one(log) return redirect('/') else: log = {"date": datetime.datetime.now(), "type": "login", "result": "wrongpw", "username": request.form['username'], "ip": request.remote_addr} dbhandler.col_logs.insert_one(log) return newrender('title_login', '', 'login_err.html', 'login_err_pw') except (IndexError, TypeError): log = {"date": datetime.datetime.now(), "type": "login", "result": "wrongusername", "username": request.form['username'], "ip": request.remote_addr} dbhandler.col_logs.insert_one(log) return newrender('title_login', '', 'login_err.html', 'login_err_username')
def user_login_process(): """Process user login.""" # Get form variables user_email = request.form["email"] password = request.form["password"] password_bytes = password.encode('utf-8') hashed = bcrypt.hashpw(password_bytes, bcrypt.gensalt()) user = User.query.filter_by(user_email=user_email).first() if not user: flash("Incorrect login credentials") return redirect("/user_login") if bcrypt.hashpw(password_bytes, hashed) == hashed: flash("Welcome") else: flash("Incorrect login credentials") return redirect("/user_login") session["user_id"] = user.user_id flash("Logged in") return redirect("/user_profile/%s" % user.user_id)
def test(self): hash1 = bcrypt.hashpw("Jadda", bcrypt.gensalt()) hash2 = bcrypt.hashpw("Jadda", hash1) self.assertEquals(hash1, hash2)
def hash_plaintext(): (db, cur) = util.get_dict_cursor() cur.execute(""" SELECT name, password FROM users """) fetch = cur.fetchall() for account in fetch: password = account["password"] user = account["name"] print user print password try: hashpw("password", password) except: pw_hash = hashpw(password, gensalt()) print pw_hash cur.execute(""" UPDATE users SET name = %s, password = %s WHERE name = %s """, (user, pw_hash, user)) fetch = cur.fetchall() db.commit()
def _digest(self, alg, password, salt=None): """ Helper method to perform the password digest. :param alg: The hash algorithm to use. :type alg: str - 'sha512' | 'bcrypt' :param password: The password to digest. :type password: str :param salt: The salt to use. In the case of bcrypt, when storing the password, pass None; when testing the password, pass the hashed value. :type salt: None or str :returns: The hashed value as a string. """ if alg == 'sha512': return hashlib.sha512(password + salt).hexdigest() elif alg == 'bcrypt': try: import bcrypt except ImportError: raise Exception('Bcrypt module is not installed. ' 'See local.auth.cfg.') if salt is None: rounds = cherrypy.config['auth']['bcrypt_rounds'] assert type(rounds) is int return bcrypt.hashpw(password, bcrypt.gensalt(rounds)) else: if type(salt) is unicode: salt = salt.encode('utf-8') return bcrypt.hashpw(password, salt) else: raise Exception('Unsupported hash algorithm: %s' % alg)
def isValidRegistration(self, userInfo, request): passFlag = True if not userInfo['first_name'].isalpha(): passFlag = False if len(userInfo['first_name']) < 2: passFlag = False if not userInfo['last_name'].isalpha(): passFlag = False if len(userInfo['last_name']) < 2: passFlag = False if not EMAIL_REGEX.match(userInfo['email']): passFlag = False if len(userInfo['password']) < 7: passFlag = False if userInfo['password'] != userInfo['confirm_password']: passFlag = False if User.objects.filter(email = userInfo['email']): passFlag = False if passFlag: if User.userManager.all: status = 1 hashed = bcrypt.hashpw(userInfo['password'].encode(), bcrypt.gensalt()) self.create(first_name = userInfo['first_name'], last_name = userInfo['last_name'], email = userInfo['email'], password = hashed, status=status) else: status = 9 hashed = bcrypt.hashpw(userInfo['password'].encode(), bcrypt.gensalt()) self.create(first_name = userInfo['first_name'], last_name = userInfo['last_name'], email = userInfo['email'], password = hashed, status=status) else: messages.error(request, "Invalid Registration. Please try again.") return passFlag
def post(self): email = self.get_argument("email", None) old_password = self.get_argument("oldpassword", None) password = self.get_argument("password", None) confirm_password = self.get_argument("confirm_password", None) errors = [] if not email: errors.append("Email cannot be blank") elif not re.match(r"^[^\s@]+@[^\s@]+\.[^\s@]{2,}$", email): errors.append("Email must be of the format '*****@*****.**'.") if not old_password: if password or confirm_password: errors.append("Current password must be supplied to change passwords.") elif (password and not confirm_password) or (confirm_password and not password): errors.append("New Password and Confirm New Password are required in order to change the current password.") elif password and confirm_password and password != confirm_password: errors.append("New password and new password confirmation must match.") elif password and confirm_password and password == confirm_password: if bcrypt.hashpw(old_password, self.current_user["password"]) != self.current_user["password"]: errors.append("The old password supplied is not correct, no updates were made to the user.") if len(errors) == 0: user = self.current_user self.db.users.update({"_id": user["_id"]}, {"$set": {"email": email}}) if password: self.db.users.update( {"_id": user["_id"]}, {"$set": {"password": bcrypt.hashpw(password, bcrypt.gensalt())}} ) self.render("myaccount.html", email=email, notifications=["Account successfully updated"]) else: self.render("myaccount.html", errors=errors, email=email if email else "")
def signin(): signin_name = request.form['username'] signin_password = request.form['password'].encode('utf-8') hashed = bcrypt.hashpw(signin_password, bcrypt.gensalt()) print 'password: %r' % hashed query_string = "select chirper.username as name, chirper.password as password, chirper.id as id from chirper where chirper.username = $1" query = db.query(query_string, signin_name) if query.namedresult(): name = query.namedresult()[0].name password = query.namedresult()[0].password user_id = query.namedresult()[0].id else: return redirect('/login') print 'name: ' + name if query: if signin_name == name and bcrypt.hashpw(signin_password, password) == password: session['username'] = signin_name session['id'] = user_id return redirect('/timeline') elif signin_name == name and bcrypt.hashpw(signin_password, password) != password: return redirect('/login') elif signin_name != name and bcryptpw(signin_password, password) != password: return redirect('/signup') else: pass else: return redirect('/login')
def bcrypt_check_password(self, raw_password): """ Returns a boolean of whether the *raw_password* was correct. Attempts to validate with bcrypt, but falls back to Django's ``User.check_password()`` if the hash is incorrect. If ``BCRYPT_MIGRATE`` is set, attempts to convert sha1 password to bcrypt or converts between different bcrypt rounds values. .. note:: In case of a password migration this method calls ``User.save()`` to persist the changes. """ pwd_ok = False should_change = False if self.password.startswith('bc$'): salt_and_hash = self.password[3:] pwd_ok = bcrypt.hashpw(smart_str(raw_password), salt_and_hash) == salt_and_hash if pwd_ok: rounds = int(salt_and_hash.split('$')[2]) should_change = rounds != get_rounds() elif _check_password(self, raw_password): pwd_ok = True should_change = True if pwd_ok and should_change and is_enabled() and migrate_to_bcrypt(): self.set_password(raw_password) salt_and_hash = self.password[3:] assert bcrypt.hashpw(raw_password, salt_and_hash) == salt_and_hash self.save() return pwd_ok
def changepass(): form = ChangePassForm() error = None if form.validate_on_submit(): user = User.query.filter_by(username=session.get('username')).first() hashed_password = bcrypt.hashpw(form.old_password.data, user.password) if form.old_password.data == form.password.data: error = "New password can't be the same as the old one" else: if hashed_password == user.password: salt = bcrypt.gensalt() new_hashed_password = bcrypt.hashpw(form.password.data, salt) user.password = new_hashed_password db.session.commit() current_ip = socket.gethostbyname(socket.gethostname()) email_subj = "Password change - GandhiWeb" email_body = "You just changed your password on GandhiWeb, if this is not the case please contact Kishen. IP address used to change password: "******"Password changed succesfully, please login again with new password") session.pop('username') session.pop('fullname') session.pop('is_admin') return redirect(url_for('index')) else: error = "Incorrect old password" return render_template('user/changepass.html', form=form, error=error)
def post(self): user = self.get_argument('name', '') pw = self.get_argument('pw', '') next = self.get_argument('next', '/') if not next.startswith('/'): next = '/' u = self.db.get('select id, display_name, password, ff2_password ' + 'from users where lower_name=%s', user.lower()) if u: if u.ff2_password: if hashlib.md5(pw).hexdigest() == u.ff2_password: self.db.execute('update users set password=%s, ' + 'ff2_password=NULL, ' + 'claimed_at=NOW(), ' + 'claimed_by_ip=%s where id=%s', bcrypt.hashpw(pw, bcrypt.gensalt()), self.request.remote_ip, u.id) self.set_secure_cookie(cookie_name, u.display_name) return self.redirect(next) elif u.password: if bcrypt.hashpw(pw, u.password) == u.password: self.db.execute('update users set ' + 'claimed_by_ip=%s where id=%s', self.request.remote_ip, u.id) self.set_secure_cookie(cookie_name, u.display_name) return self.redirect(next) return self.get(user=user, flash='Sign In Failed.')
def authenticate(self, username=None, password=None): # Try to authenticate with default backend try: # Return the local user, if login/pass match user = User.objects.get(username=username) if user.check_password(password): return user # Only the password is invalid. It is maybe outdated in database ppp_pw = self.get_blowfish_passwd(username) if ppp_pw and bcrypt.hashpw(password, ppp_pw) == ppp_pw: user.set_password(password) user.save() return user # There is no local user except User.DoesNotExist: ppp_pw = self.get_blowfish_passwd(username) # Credentials are ok, create a user in database if ppp_pw and bcrypt.hashpw(password, ppp_pw) == ppp_pw: user = User(username=username) user.set_password(password) user.save() return user # Invalid credentials return None
def main(): ''' Generate a hashed password suitable for inserting into the clients table in the database. Expects one argument: the plain text password. ''' password = sys.argv[1] print bcrypt.hashpw(password, bcrypt.gensalt())
def bo_administrator_change_password(self): try: logger.info('Handling /backoffice/users/change-password.') if self.method == 'POST': stream = BytesIO(self.body) data = JSONParser().parse(stream) if not 'current_password' in data or not 'new_password' in data: return HttpResponse(status=401) current_password = data['current_password'].encode('utf-8') new_password = data['new_password'].encode('utf-8') token = self.META.get('HTTP_AUTHORIZATION', None) user = jwt_util.jwt_auth_get_user(token) if not bcrypt.hashpw(current_password, user.password.encode('utf-8')) == user.password.encode('utf-8'): raise CustomErrorMessages(CustomErrorMessages.INVALID_CREDENTIALS) hashed_password = bcrypt.hashpw(new_password, bcrypt.gensalt()) user.password = hashed_password user.save() return HttpResponse(status=200) else: return HttpResponse(status=405) except CustomException as ce: return HttpResponse(ce.message, status=450) except: logger.error(traceback.format_exc()) return HttpResponse(CustomErrorMessages.UNEXPECTED_ERROR, status=500)
def login(): if request.method == 'POST': user = g.db.execute('select * from users where username=?', (request.form.get('username'),)).fetchall() user_exists = len(user)!=0 if request.form.get('login')!=None: if request.form.get('username')==None: return redirect(url_for("index")) if not user_exists: flash(u'No account with this username exists','login error') return redirect(url_for("index")) pw_sql = g.db.execute('select pw_hash from users where username=?', (request.form.get('username'),)) pw_hash = pw_sql.fetchall()[0][0] pw_plain = request.form.get('password').encode('UTF-8') if bcrypt.hashpw(pw_plain, pw_hash) == pw_hash: #app.logger.debug('success!') session['logged_in'] = True session['username'] = request.form.get('username') session['uid'] = user[0][0] return redirect(url_for("games")) else: flash(u'Wrong Password','login error') return redirect(url_for("index")) elif request.form.get('register')!=None: if(user_exists): flash(u'Username already taken','login error') return redirect(url_for("index")) pw_plain = request.form.get('password').encode('UTF-8') pw_hash = bcrypt.hashpw(pw_plain, bcrypt.gensalt()) g.db.execute('insert into users (username, pw_hash) values (?, ?)', (request.form.get('username'),pw_hash)) g.db.commit() return redirect(url_for("games"))
def changeuser_submit(): try: user = dbhandler.col_members.find_one({"username": session['username']}) data = {} if bcrypt.hashpw(request.form['password_now'].encode("UTF-8"), user['password']) == user['password']: if request.form['password_new'] != '': if re.match('^.{6,200}$', request.form['password_new']): if request.form['password_new'] == request.form['password_new_re']: user['password'] = bcrypt.hashpw(request.form['password_new'].encode("UTF-8"), bcrypt.gensalt(configs.bcrypt_round)) else: return newrender('title_user', filename='basic_display.html', mode='changeuser_err_pw_match') else: return newrender('title_user', filename='basic_display.html', mode='changeuser_err_pw_format') if re.match(u'^[가-힣A-Za-zぁ-ゔァ-ヴー々〆〤 ]{2,30}$', request.form['name']): user['name'] = request.form['name'] else: return newrender('title_user', filename='basic_display.html', mode='changeuser_err_name') #if re.match('^[a-zA-Z._+\\-0-9]+@[a-z0-9.\\-]+\\.[a-z]{2,5}$', request.form['email']): #user['email'] = request.form['email'] #else: # return newrender('title_user', '', 'changeuser_err.html', 'changeuser_err_email') dbhandler.col_members.update({'_id': user['_id']}, {"$set": user}, upsert=False) return newrender('title_user', filename='basic_display.html', mode='changeuser_complete') else: return newrender('title_user', filename='basic_display.html', mode='changeuser_err_pw') except KeyError: return newrender('title_user', filename='basic_display.html', mode='changeuser_err_unknown')
def setPass(): if request.method == "POST": id = request.form["id"] newPass = request.form["newPass"] newSalt = str(bcrypt.gensalt()) newHashed = bcrypt.hashpw(newPass.encode("utf-8"), newSalt) oldPass = request.form["oldPass"] cursor.execute("EXEC GetSalt @id='" + id + "'") oldSalt = cursor.fetchall()[0]["Salt"] oldHashedPass = bcrypt.hashpw(oldPass.encode("utf-8"), oldSalt.encode("utf-8")) cursor.execute( "EXEC ChangePassword @newpass = %s,@newsalt = %s,@oldpass= %s,@id= %s,@result=''", (newHashed, newSalt, oldHashedPass, id), ) ans = cursor.fetchall()[0]["result"] conn.commit() return ans else: cursor.execute("EXEC GetThemes") results = cursor.fetchall() return render_template("settings.html", themes=results)
def determine_bcrypt_cost(password_length, duration): """ Determines the cost needed for hashing to take approximately `duration` seconds. The same caveats as for :func:`determine_pbkdf2_rounds` apply. """ if bcrypt is None: raise RuntimeError("requires py-bcrypt >= 0.3") round_measure = previous_round_measure = 12 while True: start = time.clock() bcrypt.hashpw( _generate_password(password_length), bcrypt.gensalt(round_measure) ) end = time.clock() elapsed = end - start if elapsed < duration: if previous_round_measure > round_measure: round_measure += 1 # rounding up... break previous_round_measure = round_measure round_measure += 1 else: if previous_round_measure < round_measure: break previous_round_measure = round_measure round_measure -= 1 return round_measure
def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: print "Creating groups..." DBSession.add(Group(desc=Group.ADMIN)) DBSession.add(Group(desc=Group.GUEST)) DBSession.add(Group(desc=Group.TEACHER)) DBSession.add(Group(desc=Group.STUDENT)) print "Creating guest..." guestgroup = DBSession.query(Group).filter_by(desc=Group.GUEST).first().id guesthash = bcrypt.hashpw('', bcrypt.gensalt()) DBSession.add(User(username=User.GUEST, group=guestgroup, phash=guesthash)) print "Creating superuser..." admingroup = DBSession.query(Group).filter_by(desc=Group.ADMIN).first().id adminpw = getpass.getpass() adminhash = bcrypt.hashpw(adminpw, bcrypt.gensalt()) DBSession.add(User(username=User.ADMIN, group=admingroup, phash=adminhash))
def check_password(self, password): pwtmp = bcrypt.hashpw(password.encode('utf-8'), self.pw_hash.encode('utf-8')) print pwtmp pwtmp = pwtmp + password.encode('utf-8') pwtmp2 = bcrypt.hashpw(pwtmp, self.pw_hash.encode('utf-8')) print pwtmp2 return pwtmp2 == self.pw_hash.encode('utf-8')
def hashpass(s, hashpw=None, workfactor=10): """Hashes a given string (usually a password) using bcrypt. Call it with just a password to hash it for the first time. To check a user-supplied password for correctness, call it with the user-given password and the hashed password from a previous call to hashpass(), and check that the output matches the hashed password. This is the right way to hash passwords. (See http://codahale.com/how-to-safely-store-a-password/ ) Do NOT use the old makesalt() function...bcrypt generates special salts and prepends them to generated hashes, to prevent having to store them separately. Thus, you can simply call hashpass(tocheck, hashedpasswd) to check a password for validity, without screwing around with concatenating salts or storing them separately in databases. This is portable across all implementations of bcrypt (tested using python's py-bcrypt and Ruby's bcrypt-ruby). The workfactor determines the exponential cost of hashing a password. In early 2011, a workfactor of 10 (the current default) takes about .01 seconds to run, which is a good compromise between speed and slowness (for protecting against brute-force attacks). The resulting hashed password is 60 characters long, and can include letters, digits, and [$./] """ import bcrypt if hashpw: return bcrypt.hashpw(s, hashpw) return bcrypt.hashpw(s, bcrypt.gensalt(workfactor))
def test_01__gensalt(self): for plain, salt, expected in test_vectors: for i in range(4,14,2): salt = bcrypt.gensalt(i) crypted = bcrypt.hashpw(plain, salt) crypted2 = bcrypt.hashpw(plain, crypted) self.assertEqual(crypted, crypted2)
def _check_password(password_hash,password): import bcrypt import config if password_hash is None: dummy = bcrypt.hashpw(password, config.BCRYPT_SALT) _s_comp(dummy,dummy) return False return _s_comp(password_hash, bcrypt.hashpw(password,config.BCRYPT_SALT))
def bcrypt_password(password): salt = bcrypt.gensalt(log_rounds=g.bcrypt_work_factor) return bcrypt.hashpw(password, salt)
def hash_password(passwd): salt = bcrypt.gensalt() return bcrypt.hashpw(passwd.encode('utf-8'), salt)
def password_matches(user, password): ''' Return true if a user password matches the argument `password`, false otherwise ''' return bcrypt.hashpw(password, user.get('salt')) == user.get('password')
def __init__(self, login, password, first_name, last_name): self.login = login self.password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') self.first_name = first_name self.last_name = last_name
def __init__(self, username, email, password): self.email = email self.username = username self.password = bcrypt.hashpw(password, bcrypt.gensalt()) self.admin = False self.created = datetime.now()
def matchPass(password, hashed): return bcrypt.hashpw(password.encode('utf-8'), hashed.encode('utf-8')) == hashed
def password(self, passwd): self._password = bcrypt.hashpw((passwd + config['secret']).encode(), bcrypt.gensalt()).decode()
import os import bcrypt #os.system('time hashcat -m 10 -a 0 -O --potfile-path=/Users/Bastian/desktop/tarea_4/archivo_2/my.pot.txt /Users/Bastian/desktop/tarea_4/archivo_2/archivo_2 /Users/Bastian/desktop/tarea_4/diccionario_2.dict --force') f = open("my.pot.txt", "r") #abre potfile, lee las contrasenas y las hashea 1 x 1. f2 = open("salida_hasheada.txt", "a+") a = f.read().split('\n') for i in range(0, len(a)-1): b = a[i].split(':') print(b[2]) c = bytes(b[2], 'utf-8') salt = bcrypt.gensalt() hashed = bcrypt.hashpw(c, salt) f2.write(hashed.decode("utf-8") + '\n' ) print(hashed) f.close() f2.close()
def set_password(self, pw): password = bcrypt.hashpw(pw.encode('utf8'), bcrypt.gensalt()) self.password_hash = password.decode('utf8')
import pymongo import hashlib import bcrypt from setuptools import setup setup( name='instaNAS', version='1.0', description='Simple NAS Application Server', author='Praveen M Nair', author_email='*****@*****.**', url='http://www.python.org/sigs/distutils-sig/', install_requires=['tornado', 'pymongo', 'py-bcrypt'], ) dbconn = pymongo.MongoClient('mongodb://localhost:27017/') db = dbconn['insta-nas-db']['admins'] admin = db.find_one({'user': '******'}) if admin: db.remove({'user': '******'}) phash = bcrypt.hashpw('admin'.encode('utf-8'), bcrypt.gensalt(8)) u = {} u['user'] = '******' u['password'] = phash u['secret'] = hashlib.sha1('admin/%s' % (phash)).hexdigest() db.save(u)
def signup(): if request.method == "POST": allgood = True session["firstname"] = request.form["input_firstname"] session["lastname"] = request.form["input_lastname"] session["username"] = request.form["input_username"] session["useremail"] = request.form["input_email"] session["birthdate"] = datetime.strptime( request.form["input_birthdate"], '%Y-%m-%d') password1 = request.form["input_password1"] password2 = request.form["input_password2"] today = to_integer(date.today()) birthdate = to_integer(session["birthdate"]) age = today - birthdate tempuser = users.query.filter_by(username=session["username"]).first() if tempuser: flash("username alrady existe, try another one.") allgood = False if re.search(r'\d', session["firstname"]): flash(" fits name must be letters only") allgood = False if re.search(r'\d', session["lastname"]): flash(" last name must be letters only") allgood = False if re.search(r'[^a-zA-Z0-9]', session["username"]): flash("username must be letters and numbers only") allgood = False if pinger.test_if_real(session["useremail"]): flash("email is not valid") allgood = False if age < 180000: flash("to yuong 2 die") allgood = False if password1 != password2: flash("passowrs dont match") allgood = False if how_strong.how_strong(password1) < 500: flash("passowr are too weak ") allgood = False if allgood: password = password1.encode("utf-8") session["password"] = bcrypt.hashpw(password, bcrypt.gensalt()) newuser = users(session["firstname"], session["lastname"], session["username"], session["useremail"], session["birthdate"], session["password"], datetime.now()) db.session.add(newuser) db.session.commit() return redirect(url_for("home")) return render_template("signup.html")
def hashPassword(pwd): if type(pwd) is str: pwd = pwd.encode("utf-8") return bcrypt.hashpw(pwd, bcrypt.gensalt())
def checkPassword(hash, pwd): if type(pwd) is str: pwd = pwd.encode("utf-8") if type(hash) is str: hash = hash.encode("utf-8") return bcrypt.hashpw(pwd, hash) == hash
domain = d.get_input("PrestaShop Domain", "Enter the domain to serve Prestashop.", DEFAULT_DOMAIN) if domain == "DEFAULT": domain = DEFAULT_DOMAIN inithooks_cache.write('APP_DOMAIN', domain) for line in file( '/var/www/prestashop/app/config/parameters.php').readlines(): m = re.match(" *'cookie_key' => '(.*)',", line.strip()) if m: cookie_key = m.group(1) hashpass = bcrypt.hashpw(password, bcrypt.gensalt()) m = MySQL() m.execute( 'UPDATE prestashop.ps_employee SET email=\"%s\" WHERE id_employee=\"1\";' % email) m.execute( 'UPDATE prestashop.ps_employee SET passwd=\"%s\" WHERE id_employee=\"1\";' % hashpass) m.execute( 'UPDATE prestashop.ps_configuration SET value=\"%s\" WHERE name=\"PS_SHOP_DOMAIN\";' % domain) m.execute( 'UPDATE prestashop.ps_configuration SET value=\"%s\" WHERE name=\"PS_SHOP_DOMAIN_SSL\";' % domain) m.execute(
import bcrypt password = "******" salt = bcrypt.gensalt(2) hashed = bcrypt.hashpw(password, salt) # Check that an unencrypted password matches one that has # previously been hashed hashed2 = bcrypt.hashpw(password, hashed) print hashed2 if hashed2 == hashed: print "It matches" else: print "It does not match"
def add_creds(username, password, email, phoneNumber): password_hash = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt()) cur.execute(" INSERT INTO users VALUES (?,?,?,?) ", (username, password_hash, email, phoneNumber)) conn.commit() return None
def hashPass(password): return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
def hash_password(password): # Store password safely in database as str # (bcrypt.hashpw returns base64 bytes). pwd_str = password.encode(encoding="utf-8") hashed = bcrypt.hashpw(pwd_str, bcrypt.gensalt()) return hashed.decode(encoding="utf-8")
def generate_password_hash(password: Any) -> str: if isinstance(password, text_type): password = password.encode('utf-8') return bcrypt.hashpw(password, bcrypt.gensalt(prefix=b'2a')).decode('utf-8')
return render(request, "users/index.html", context) ############################## ### Email Regex ############################## import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') ############################## ### Bcrypt ############################## import bcrypt ## creating a user with a hashed_pw hashed_pw = bcrypt.hashpw(postData['password'].encode('utf-8'), bcrypt.gensalt()) u = User.objects.create(email = postData['email'], password = hashed_pw) ## checking if a password matches u = User.objects.get(email = "*****@*****.**") stored_hash = u.password input_hash = bcrypt.hashpw(postData['password'].encode(), stored_hash.encode()) if not input_hash == stored_hash: errors.append("Invalid Email/Password") ############################## ### Views.py and urls.py ##############################
def hash_password(plaintext_password): salt = bcrypt.gensalt() password_hash = bcrypt.hashpw(plaintext_password.encode("utf-8"), salt) return password_hash.decode()
def hashpwd(password): hash = bcrypt.hashpw(password, bcrypt.gensalt()) return hash
def verified_password(username: str, password: str): if not user_exist(username): return False db_password = users.find_one({"Username": username})["Password"] return True if bcrypt.hashpw(password.encode( encoding='UTF-8'), db_password) == db_password else False
def register(self, post): encrypted_password = bcrypt.hashpw(post['password'].encode(), bcrypt.gensalt()) User.objects.create(name = post['name'], alias = post['alias'], email = post['email'],birthdate = post['birthdate'], password = encrypted_password )
def encrypt_password(cls, password): hash_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) return hash_password
def set_password(self, password): self.password = bcrypt.hashpw(password, bcrypt.gensalt())
db.commit() except Exception as e: db.rollback() return jsonify(message=f"{e}"), 500 finally: if db: db.close() #이메일 회원가입 @user_app.route('/sign-up', methods=['POST']) def sign_up() try: db = db_connector() data = request.json data['password'] = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt()) db.begin() model_dao.create_user(db, data['email'], data['password'], data['nickname']) db.commit() return '', 200 except Exception as e: db.rollback() return jsonify(message = f'{e}'), 500 finally: if db: db.close() #이메일 중복 확인
def valid_password(cls, password_typed, hash_password): return bcrypt.hashpw(password_typed.encode('utf-8'), hash_password) == hash_password
from db.users import Users # Create the database if it doesn't exist if not database_exists(engine.url): create_database(engine.url) # Create the user table Base.metadata.create_all(engine) # Create the user with id 1 DEMO = { 'id': 1, 'username': '******', 'password': '******', 'first_name': 'Kevin', 'last_name': 'Rivers' } # Hash user password with bcrypt(12) DEMO['password'] = bcrypt.hashpw(DEMO['password'].encode(), bcrypt.gensalt()).decode() u = Users(**DEMO) session.add(u) try: session.commit() except IntegrityError: # We have already added the demo user with id 1 pass
def get_hash(password: str): password = password.encode('utf8') password = bcrypt.hashpw(password, bcrypt.gensalt()).decode('utf8') return password