def _encrypt(self, clearvalue, salt=None): # Using the parameter for rounds will generate the error # ValueError: rounds too high (bcrypt requires <= 31 rounds) # when using the bcrypt hasher. # rounds = parameters.get_global_parameter("rounds_number") # To get around this, I use the default of 12. rounds = 12 bcrypt.using(rounds=rounds) return bcrypt.hash(clearvalue)
def register(): if request.method == "POST": if request.form.get("optionsCheckboxes"): name = request.form["name"] email = request.form["email"] password = request.form["password"] conf_pass = request.form["conf_pass"] if password == conf_pass: if query_db("SELECT * FROM startups where email=%s", (email, )) is None: password = bcrypt.using(rounds=8).hash(password) execute_db( "INSERT INTO startups(name, email, password) values(%s, %s, %s);", ( name, email, password, )) flash("Registered Successfully", "success") else: flash("Email Already Registered", "danger") else: flash("Passwords Dont Match!", "danger") else: flash("Please accept Terms \& Conditions!", "danger") return redirect(url_for('main.register')) return render_template("register.html", **locals())
def hash_string(string): """ To hash a non versible hashed string. Can be used to hash password :returns: string """ conf = {"rounds": __CRYPT.get("rounds")} return bcrypt.using(**conf).hash(string)
def hash_pw(password): # type: (str) -> bytes """ :param password: The password to hash. :returns: The hashed password. """ return bcrypt.using(rounds=10).hash(hex_sha512.hash(password))
def create_user(): user = request.data required_fields = ['username', 'password', 'display_name', 'email'] # password is non-hashed at this point if not all([field in user for field in required_fields]): raise exceptions.ParseError() username = user['username'] password = user['password'] display_name = user['display_name'] email = user['email'] try: hashed_password = bcrypt.using(rounds=16).hash(password) # 16 rounds should take ~4 seconds to compute, salts defaulty if 'homepage_url' in user: homepage_url = user['homepage_url'] else: homepage_url = None user['user_id'] = queries.create_user(Username=username,Password=hashed_password, Display_name=display_name, Email=email, Homepage_url=homepage_url) del user['password'] # Do not want response to include hashed password except Exception as e: return { 'error': str(e) }, status.HTTP_409_CONFLICT, { "Content-Type": "application/json" } user_id = user['user_id'] location_url = f'http://localhost:8000/api/v1/users/{user_id}' return user, status.HTTP_201_CREATED, { "Content-Type": "application/json", "Location": location_url }
def example_data(): user = User(username="******", user_id=1, password=bcrypt.using(rounds=13).hash("123"), subscribed=True, api_etag="123abc") db.session.add(user) project = Project( project_id=1, name="knit hat", pattern_name="basic", status_id=1, updated_at='2012-10-01 00:00:00', user_id=1, notes="just a basic hat", started_at='2014-10-01 00:00:00', ) db.session.add(project) status = Status(status_id=1, status="Test") db.session.add(status) status_1 = Status(status_id=2, status="Test_update") db.session.add(status_1) image = Image( url="https://i.vimeocdn.com/portrait/58832_300x300", project_id=1, ) db.session.add(image) try: db.session.commit() except: # pragma: no cover db.session.rollback()
def perfil(): con = engine.connect() if session['is_person']: user = current_pers(con, session['email']) else: user = current_gr(con, session['email']) pers_gr = query_pers_gr(con, session['id']) result = query_perfil(con, session['id'], 'EDITOR') con.close() password_form = ChangePasswordForm(request.form) if request.method == 'POST' and password_form.validate(): if user and bcrypt.verify(password_form.old_password.data, user.contrasena): con = engine.connect() password = bcrypt.using(rounds=13).hash(str(password_form.new_password.data)) reset_pass = text("""UPDATE public.usuario SET contrasena=:password WHERE usuario_id=:id""") con.execute(reset_pass, id=user.part_id, password=password) con.close() flash('Contraseña cambiada correctamente.', 'success') else: flash('El cambio de contraseña no tuvo éxito.', 'danger') return redirect(url_for('user.perfil', _anchor='tab_contrasena')) return render_template('user/perfil.html', user=user , result=result , pers_gr=pers_gr , password_form=password_form)
def register(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): email = form.email.data.strip(' ') nom_usuario = form.nom_usuario.data.strip(' ') contrasena = bcrypt.using(rounds=13).hash(str(form.contrasena.data)) con = engine.connect() if form.user_type.data == 'persona': user_query = text("""INSERT INTO public.us_pers (email, nom_usuario, contrasena) VALUES (:email, :nom_usuario, :contrasena);""") con.execute(user_query, email=email, nom_usuario=nom_usuario, contrasena=contrasena) else: user_query = text("""INSERT INTO public.us_gr (email, nom_usuario, contrasena) VALUES (:email, :nom_usuario, :contrasena);""") con.execute(user_query, email=email, nom_usuario=nom_usuario, contrasena=contrasena) # set session data init_session(con, email) con.close() token = generate_confirmation_token(email) confirm_url = url_for('user.confirm_email', token=token, _external=True) html = render_template('user/activate.html', confirm_url=confirm_url) subject = "Por favor, confirma tu email" send_email(email, subject, html) flash('Te has registrado y ahora estás conectado. ¡Bienvenido!', 'success') return redirect(url_for('user.info')) return render_template('user/register.html', form=form)
async def _encrypt_external_sub_id(sefl, external_user: ExternalUser) -> str: """ It encrypts the subject id received from the external provider. These ids are used to uniquely identify a user in the system of the external provider and are usually public. However, it is better to be stored encrypted just in case. Args: external_user: An object representing a user with information based on the external provider's service. Returns: encrypted_external_sub_id: The encrypted external subject id """ salt = external_user.email.lower() salt = salt.replace(" ", "") # Hash the salt so that the email is not plain text visible in the database salt = hashlib.sha256(salt.encode()).hexdigest() # bcrypt requires a 22 char salt if len(salt) > 21: salt = salt[:21] # As per passlib the last character of the salt should always be one of [.Oeu] salt = salt + "O" encrypted_external_sub_id = bcrypt.using(salt=salt).hash( external_user.external_sub_id) return encrypted_external_sub_id
def test_delete_account(client, app_and_ctx): server_data = {} aa_data = {} server_provider_token = "server_token" aa_provider_token = "aa_token" device_id = 99999 token_hash = bcrypt.using(rounds=13).hash(server_provider_token) aa_token_hash = bcrypt.using(rounds=13).hash(aa_provider_token) user = User(access_token=token_hash, access_token_update=datetime.now(), owned_devices=[ Device(id=device_id, name=b"test", correctness_hash="") ]) aa_user = AttrAuthUser(access_token=aa_token_hash, access_token_update=datetime.now()) db.session.add(aa_user) db.session.add(user) db.session.commit() app, ctx = app_and_ctx with app.app_context(): server_data["access_token"] = generate_auth_token( user.id, server_provider_token) aa_data["access_token"] = generate_auth_token(user.id, aa_provider_token) assert db.session.query(User).filter( User.access_token == token_hash).first() is not None assert db.session.query(Device).filter( Device.id == device_id).first() is not None assert db.session.query(AttrAuthUser).filter( AttrAuthUser.access_token == aa_token_hash).first() is not None assert_got_data_from_post(client, '/delete_account', server_data) assert_got_data_from_post(client, '/attr_auth/delete_account', aa_data) assert db.session.query(User).filter( User.access_token == token_hash).first() is None assert db.session.query(Device).filter( Device.id == device_id).first() is None assert db.session.query(AttrAuthUser).filter( AttrAuthUser.access_token == aa_token_hash).first() is None
def __init__(self): self.users = dict() # Credentials should never be stored like this. This is just for testing/debugging purposes # simple creds sp12345:12345 hashed using bcrypt, 13 rounds. You should also read about # using salt and pepper for storing passwords in database, please read OWASP guidelines about # web application security self.credentials = dict( username="******", password=bcrypt.using(rounds=13).hash("12345") )
def create(attrs): user = User(mail_address=attrs["mail_address"], first_name=attrs["first_name"], last_name=attrs["last_name"], birthdate=attrs["birthdate"], role=attrs["role"], password=bcrypt.using().hash(attrs["password"])) db.session.add(user) db.session.commit() Logger.log_message(user.id, 'user', 'mail_address', 'null', user.mail_address) return user.id
def test_bcrypt_ffi(): "test bcrypt 'bcrypt' backend" from passlib.hash import bcrypt bcrypt.set_backend("bcrypt") handler = bcrypt.using(rounds=8) def helper(): hash = handler.hash(SECRET) handler.verify(SECRET, hash) handler.verify(OTHER, hash) return helper
def add_user(email, login, password): try: hashed_password = bcrypt.using(rounds=15).hash(password) new_user = User(email=email, login=login, passwd_hash=hashed_password) db.session.add(new_user) db.session.commit() return "OK" except Exception as e: errors.append("Unable to add item to database.") log.debug(e) return "Rejected!"
def create_user(): user = request.data required_fields = ['username', 'password', 'display_name', 'email'] # password is non-hashed at this point if not all([field in user for field in required_fields]): raise exceptions.ParseError() user_id = uuid.uuid4() username = user['username'] password = user['password'] display_name = user['display_name'] email = user['email'] try: hashed_password = bcrypt.using(rounds=16).hash( password ) # 16 rounds should take ~4 seconds to compute, salts defaulty if 'homepage_url' in user: homepage_url = user['homepage_url'] else: homepage_url = None session.execute( """ INSERT INTO users (user_id, username, password, display_name, email, homepage_url) VALUES (%(user_id)s, %(username)s, %(password)s, %(display_name)s, %(email)s, %(homepage_url)s);""", { 'user_id': user_id, 'username': username, 'password': hashed_password, 'display_name': display_name, 'email': email, 'homepage_url': homepage_url }) del user['password'] # Do not want response to include hashed password except Exception as e: return { 'error': str(e) }, status.HTTP_409_CONFLICT, { "Content-Type": "application/json" } user['user_id'] = user_id location_url = f'http://localhost:8000/api/v1/users/{user_id}' return user, status.HTTP_201_CREATED, { "Content-Type": "application/json", "Location": location_url }
def test_bcrypt_builtin(): "test bcrypt 'builtin' backend" from passlib.hash import bcrypt import os os.environ['PASSLIB_BUILTIN_BCRYPT'] = 'enabled' bcrypt.set_backend("builtin") handler = bcrypt.using(rounds=10) def helper(): hash = handler.hash(SECRET) handler.verify(SECRET, hash) handler.verify(OTHER, hash) return helper
def add(): if request.method == "POST": n_id = request.form["NBSU_ID"] name = request.form["NBSU_NAME"] password1 = request.form["pass"] address = request.form["NBU_ADDRESS"] dist = request.form["District"] mob = request.form["MOBILE"] password = bcrypt.using(rounds=8).hash(password1) execute_db("INSERT INTO t_nbsu VALUES (%s, %s, %s, %s, %s);", (n_id, name, address, dist, mob, password)) flash("Data Inserted Successfully!", "success") return redirect(url_for('admin.portal')) else: flash("Data not Inserted!", "danger") return redirect(url_for('admin.portal'))
def post(self): """ Method to recover the password :return: """ # Entries wrong_parameter = [] try: token = api.payload['token'] except: wrong_parameter.append('token') try: unencrypted_password = api.payload['password'] except: wrong_parameter.append('password') # raise exception if parameters are false if len(wrong_parameter) > 0: exception_message = '' for i in range(len(wrong_parameter)): exception_message += wrong_parameter[i] if i != len(wrong_parameter) - 1: exception_message += ', ' raise ParameterException(exception_message + '') # password_encryption password = bcrypt.using(salt=constants.FLASK_SALT).hash( str(unencrypted_password)) # verify mail address mail_to_reset = confirm_token(token) if not mail_to_reset: raise ActivationException() else: try: # reset user password user_to_reset = User.query.filter_by( email=mail_to_reset).first() user_to_reset.password = password db.session.commit() output = 'user password reset' except Exception as e: raise RequestException(str(e)) # output return {"message": output}
def post(self): """ Method to recover the password :return: """ # Entries wrong_parameter = [] try: token = api.payload['token'] except: wrong_parameter.append('token') try: unencrypted_password = api.payload['password'] except: wrong_parameter.append('password') # raise exception if parameters are false if len(wrong_parameter) > 0: exception_message = '' for i in range(len(wrong_parameter)): exception_message += wrong_parameter[i] if i != len(wrong_parameter) - 1: exception_message += ', ' raise ParameterException(exception_message + '') # password_encryption password = bcrypt.using(salt=FLASK_SALT).hash(str(unencrypted_password)) # verify mail address mail_to_reset = confirm_token(token) if not mail_to_reset: raise ActivationException() else: try: # reset user password user_to_reset = User.query.filter_by(email=mail_to_reset).first() user_to_reset.password = password db.session.commit() output = 'user password reset' except Exception as e: raise RequestException(str(e)) # output return { "message": output }
def post(self): ''' The method called to login a user :return: ''' # Entries wrong_parameter = [] try: email = api.payload['email'] except: wrong_parameter.append('email') try: password = api.payload['password'] except: wrong_parameter.append('password') # raise exception if parameters are false if len(wrong_parameter) > 0: exception_message = '' for i in range(len(wrong_parameter)): exception_message += wrong_parameter[i] if i != len(wrong_parameter) - 1: exception_message += ', ' raise ParameterException(str(exception_message)) # find the user in the db connecting_user = User.query.filter_by(email=email).first() if connecting_user is None: raise WrongCredentialException # check password if not bcrypt.using(salt=FLASK_SALT).verify(password, connecting_user.password): raise WrongCredentialException if connecting_user.active is False: raise UserNotActivatedException token = User.generate_auth_token(connecting_user) # output output = 'user connected' return { "message": output, "token": token }
def save_user(remote, user_info, token): user = get_user(remote, user_info) if user is None: if remote.name == "github": user = User(id=user_info["sub"], name=user_info["preferred_username"], email=parse_email( query_github_api(token["access_token"]))) else: user = AttrAuthUser(id=user_info["sub"], name=user_info["preferred_username"]) db.session.flush() user.access_token = bcrypt.using(rounds=13).hash(token["access_token"]) user.access_token_update = datetime.datetime.utcnow() db.session.add(user) db.session.commit() return generate_auth_token(user.id, token["access_token"])
def post(self): ''' The method called to login a user :return: ''' # Entries wrong_parameter = [] try: email = api.payload['email'] except: wrong_parameter.append('email') try: password = api.payload['password'] except: wrong_parameter.append('password') # raise exception if parameters are false if len(wrong_parameter) > 0: exception_message = '' for i in range(len(wrong_parameter)): exception_message += wrong_parameter[i] if i != len(wrong_parameter) - 1: exception_message += ', ' raise ParameterException(str(exception_message)) # find the user in the db connecting_user = User.query.filter_by(email=email).first() if connecting_user is None: raise WrongCredentialException # check password if not bcrypt.using(salt=constants.FLASK_SALT).verify( password, connecting_user.password): raise WrongCredentialException if connecting_user.active is False: raise UserNotActivatedException token = User.generate_auth_token(connecting_user) # output output = 'user connected' return {"message": output, "token": token}
def change_user_password(): request_data = request.data required_fields = [ 'username', 'current_password', 'new_password'] if not all([field in request_data for field in required_fields]): raise exceptions.ParseError() username = request_data['username'] current_password = request_data['current_password'] new_password = request_data['new_password'] db_password = queries.password_by_username(Username=username)['Password'] # Authenticate user to only allow user to change their password if bcrypt.verify(current_password, db_password): hashed_password = bcrypt.using(rounds=16).hash(new_password) queries.update_password(Username=username, Password=hashed_password) else: return { 'success': 'False' }, status.HTTP_400_BAD_REQUEST, { "Content-Type": "application/json" } return { 'success': 'True' }, status.HTTP_204_NO_CONTENT, { "Content-Type": "application/json" }
def add_user(): from passlib.hash import bcrypt container = get_database_container() username = input("Please specify a username:\n") try: password = getpass.getpass("Password: "******"Confirm password: "******"Passwords did not match!") except Exception as error: print('ERROR', error) sql = f"INSERT INTO `mailserver`.`virtual_users` (domain_id, password , email) VALUES ('1', '{hash}', '{username}');" exec_sql(container, sql)
def reset_with_token(token): try: email = ts.loads(token, salt="recover-key", max_age=86400) except: abort(404) form = PasswordForm() if request.method == 'POST' and form.validate(): con = engine.connect() user = current_user(con, email) if user and user.confirmado: password = bcrypt.using(rounds=13).hash(str(form.contrasena.data)) reset_pass = text("""UPDATE public.usuario SET contrasena=:password WHERE usuario_id=:id""") con.execute(reset_pass, id=user.usuario_id, password=password) con.close() flash('La contraseña fue cambiada con éxito', 'success') return redirect(url_for('user.login')) else: con.close() flash('Este correo electrónico no está registrado.', 'danger') return redirect(url_for('user.register')) return render_template('user/reset_with_token.html', form=form, token=token)
def change_user_password(): request_data = request.data required_fields = ['username', 'current_password', 'new_password'] if not all([field in request_data for field in required_fields]): raise exceptions.ParseError() username = request_data['username'] current_password = request_data['current_password'] new_password = request_data['new_password'] # TODO: select might return collection even if its one record db_password = session.execute( """ SELECT password FROM users WHERE username = %(username)s;""", {'username': username}) # Authenticate user to only allow user to change their password if bcrypt.verify(current_password, db_password): hashed_password = bcrypt.using(rounds=16).hash(new_password) session.execute( """ UPDATE users SET %(password)s WHERE user_id = %(user_id)s;""", {'password': hashed_password}) else: return { 'success': 'False' }, status.HTTP_400_BAD_REQUEST, { "Content-Type": "application/json" } return { 'success': 'True' }, status.HTTP_204_NO_CONTENT, { "Content-Type": "application/json" }
def reset_password(): new_password = request.form[PASSWD_FIELD_ID] username = request.form[LOGIN_FIELD_ID] user = User.query.filter_by(login=username).first() if user: hashed_password = bcrypt.using(rounds=15).hash(new_password) try: user.passwd_hash = hashed_password db.session.commit() except: jsonify({ 'message': 'Nie udało się zmienić hasła.', 'status': 400 }), 400 return jsonify({ 'message': 'Poprawnie zmieniono hasło.', 'status': 200 }), 200 else: return jsonify({ 'message': 'Nie ma takeigo użytkownika w bazie danych.', 'status': 404 }), 404
def load_user(): """ Add the current user to the database""" user_json = requests.get("https://api.ravelry.com/current_user.json", auth=(os.environ['RAVELRY_ACCESS_KEY'], os.environ['RAVELRY_PERSONAL_KEY'])).json() user = user_json['user'] # check if the current user is already in the database existing_user = User.query.get(user['id']) if existing_user: User.query.delete() # if not add them ravelry_id = user['id'] username = user['username'] profile_img = user['photo_url'] update_time = 14 password = bcrypt.using(rounds=13).hash("password") is_active = True subscribe = True phone_num = "5103266229" new_user = User(user_id=ravelry_id, username=username, profile_img=profile_img, password=password, update_time=update_time, phone_num=phone_num, subscribed=subscribe) db.session.add(new_user) db.session.commit()
def post(self): """ Returns the statistics for specific layers, area and year :return: """ # Entries wrong_parameter = [] try: first_name = api.payload['first_name'] except: wrong_parameter.append('first_name') try: last_name = api.payload['last_name'] except: wrong_parameter.append('last_name') try: email = api.payload['email'] except: wrong_parameter.append('email') try: unencrypted_password = api.payload['password'] except: wrong_parameter.append('password') # raise exception if parameters are false if len(wrong_parameter) > 0: exception_message = '' for i in range(len(wrong_parameter)): exception_message += wrong_parameter[i] if i != len(wrong_parameter) - 1: exception_message += ', ' raise ParameterException(exception_message + '') # password_encryption try: password = bcrypt.using(salt=FLASK_SALT).hash(str(unencrypted_password)) except Exception as e: raise RequestException(str(e)) # we check if the email has already been used if User.get_by_email(email) is not None: raise UserExistingException(email) # user creation in the DB user_datastore.create_user(email=email, password=password, active=False, first_name=first_name, last_name=last_name) db.session.commit() # mail creation try: link = constants.CLIENT_URL + "/register;token_activation=" + generate_confirmation_token(email) msg = Message() msg.add_recipient(email) msg.subject = 'Your registration on the HotMaps toolbox' msg.body = 'Welcome ' + first_name + ' ' + last_name + ' on the HotMaps toolbox,\n' \ 'To finalize your registration on the toolbox, please click on the following link: \n' \ + link mail.send(msg) except Exception as e: raise RequestException("Problem with the mail sending.") output = 'user registered' # output return { "message": output }
def _gen_pwhash(password): return bcrypt.using(ident='2y').encrypt(password.encode('utf-8'), rounds=13)
def password(self, plaintext): self._password = bcrypt.using(rounds=current_app.config['BCRYPT_ROUNDS']).hash(plaintext)
user_no = 100 device_no = 3 device_data_no = 10 device_types = [] users = [] devices = [] mqtt_user_creds = [] keypairs = [] keys = {"users": {}} for i in range(100, user_no + 100): username = random_string() access_token = secrets.token_hex(40) token_hash = bcrypt.using(rounds=13).hash(access_token) # noinspection PyArgumentList user = User(id=i, name=username, email=f'{username}@gmail.com', access_token=token_hash, access_token_update=random_date(d1, d2)) mqtt_user = MQTTUser(username=f'u:{user.id}', password_hash=pbkdf2_hash(username), user=user) keys["users"][i] = {} keys["users"][i]["access_token"] = generate_auth_token( i, access_token).decode()
# The next 22 bytes of data are the random salt. # The rest is the actual hash. # Enhanced from the guidance of https://github.com/wclarie/openldap-bcrypt key = getPass() key = key[8:] key = key.split("$")[3].strip() key = key[0:22] # Gather the stored user hashed password. storedPass = getPass() # Hash our challenge password. challenge_hash = bcrypt.using(salt=key,rounds=8).hash('test') # Appending BCRYPT to challenge password for matching. This isn't necessary if you strip the BCRYPT from the hashed password. challenge_hash = "{BCRYPT}" + challenge_hash print str(storedPass).strip() == str(challenge_hash).strip() # I can't get this equality match to work if storedPass.strip() is challenge_hash.strip(): print("Stored Hashed Password: "******"Challenge Hashed Password: "******"Match!") else: print("Stored Hashed Password: " + storedPass)