我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用bcrypt.gensalt()。
def auth_update_cache(self): if '' in self.ctx.cache_db: # Cache disabled? return key = self.username + ':' + self.domain now = self.now # For tests snow = str(now) try: salt = bcrypt.gensalt(rounds=self.ctx.bcrypt_rounds) except TypeError: # Old versions of bcrypt() apparently do not support the rounds option salt = bcrypt.gensalt() pwhash = bcrypt.hashpw(self.password, salt) if key in self.ctx.cache_db: (ignored, ts1, tsv, tsa, rest) = self.ctx.cache_db[key].split("\t", 4) self.ctx.cache_db[key] = "\t".join((pwhash, ts1, snow, snow, rest)) else: self.ctx.cache_db[key] = "\t".join((pwhash, snow, snow, snow, '')) self.try_db_sync()
def __setattr__(self, name, value): """ Overide __setattr__ to update dict value and field value at once """ object.__setattr__(self, name, value) if name in self.dictValues: # If updating a field value if self._meta.fields[name].salt: # field is salt # If field is already salt do nothing. # XXX Could create a security issue. What happend is value # starts with $2b$ but it's not encrypted. Not critical for now if not ("$2b$" in value and value[:4] == "$2b$"): value = bcrypt.hashpw(value.encode('utf8'), bcrypt.gensalt()) object.__setattr__(self, name, value) # If value is an instance of model class and has a relation. # Append it to the corresponding field list if hasattr(value, "_meta") and self.isForeignKey(self._meta.fields[name]): self.dictValues[name] = getattr(value, self._meta.fields[name].reference.name) return self.dictValues[name] = value
def register(request): check = User.objects.validateUser(request.POST) if request.method != 'POST': return redirect('/') if check[0] == False: for error in check[1]: messages.add_message(request, messages.INFO, error, extra_tags="registration") return redirect('/') if check[0] == True: #has password hashed_pw = bcrypt.hashpw(request.POST.get('password').encode(), bcrypt.gensalt()) #create user user = User.objects.create( first_name = request.POST.get('first_name'), last_name = request.POST.get('last_name'), email = request.POST.get('email'), password = hashed_pw, ) #add user to session, logging them in request.session['user_id'] = user.id #route to user profile page return redirect('/user')
def signup(self, postData): errors = [] response = {} #Validate form data if not EMAIL_REGEX.match(postData['email']): error.append('Email error') if postData['password'] != postData['confirm_password']: errors.append('Confirm password did not match.') elif not PASSWORD_REGEX.match(postData['password']): errors.append('Password must blah.') #Compile errors and send to response messages if errors: response['status'] = False response['errors'] = errors else: response['status'] = True response['user'] = self.create( email=postData['email'], first_name=postData['first_name'], last_name=postData['last_name'], password=bcrypt.hashpw(postData['password'].encode('utf-8'),bcrypt.gensalt()) ) return response
def save(self, graph, raw_view_pass, raw_edit_pass, force=False): if raw_view_pass: view_pass = bcrypt.hashpw( raw_view_pass.encode(), bcrypt.gensalt()).decode() else: view_pass = self.view_pass if raw_edit_pass: edit_pass = bcrypt.hashpw( raw_edit_pass.encode(), bcrypt.gensalt()).decode() else: edit_pass = self.edit_pass cur = self._db.cursor() cur.execute('''update polycules set graph = ?, view_pass = ?, delete_pass = ? where id = ?''', [graph, view_pass, edit_pass, self.id]) self._db.commit() self.graph = graph self.view_pass = view_pass self.edit_pass = edit_pass
def set_user_credentials(user): username = user['username'] entry = get_user_entry(username) if not entry : salt = bcrypt.gensalt() passwd = gen_hash(user['password'], salt) app_key = generate_key() set_user = AppAuthentication( username=username, password=passwd, api_key=app_key, salt=salt ) #----- send api key to user for adding custom protocol -----# db.session.add(set_user) db.session.flush() return set_user.api_key
def register_submit(): # first, check to see if the username already exists. SELECT statement. check_username_query = "SELECT * FROM user where username = '%s'" % request.form['username'] cursor.execute(check_username_query) check_username_result = cursor.fetchone() # second, if it't not taken, then insert the username into mysql if (check_username_result is None): # no match. insert session['username'] = request.form['username'] real_name = request.form['real_name'] username = request.form['username'] password = request.form['password'].encode('utf-8') hashed_password = bcrypt.hashpw(password, bcrypt.gensalt()) email = request.form['email'] username_insert_query = "INSERT INTO user VALUES (DEFAULT, %s, %s, %s, %s, NULL)" cursor.execute(username_insert_query, (real_name, username, hashed_password, email)) conn.commit() return render_template('index.html') else: # second b, if it is taken, send them back to the register page with a message return redirect('/register?username=taken')
def register_submit(): # first, check to see if the username already exists. SELECT statement. check_username_query = "SELECT * FROM user where username = '%s'" % request.form['username'] cursor.execute(check_username_query) check_username_result = cursor.fetchone() # second, if it't not taken, then insert the username into mysql if (check_username_result is None): # no match. insert session['username'] = request.form['username'] real_name = request.form['real_name'] username = request.form['username'] password = request.form['password'].encode('utf-8') hashed_password = bcrypt.hashpw(password, bcrypt.gensalt()) email = request.form['email'] username_insert_query = "INSERT INTO user VALUES (DEFAULT, %s, %s, %s, %s, NULL)" cursor.execute(username_insert_query, (real_name, username, hashed_password, email)) conn.commit() get_id_query = "SELECT id FROM user where username = '%s'" % request.form['username'] cursor.execute(get_id_query) get_id_result = cursor.fetchone() session['id'] = get_id_result[0] return render_template('index.html') else: # second b, if it is taken, send them back to the register page with a message return redirect('/register?username=taken')
def add_user(): form = ctforge.forms.UserForm() if request.method == 'POST': if form.validate_on_submit(): query_handler(( 'INSERT INTO users (team_id, name, surname, mail, ' ' password, admin, hidden) ' 'VALUES (%s, %s, %s, %s, %s, %s, %s)'), (form.team_id.data, form.name.data, form.surname.data, form.mail.data, bcrypt.hashpw(form.password.data, bcrypt.gensalt()), form.admin.data, form.hidden.data)) else: flash_errors(form) return redirect(url_for('admin', tab='users')) return render_template('admin/data.html', form=form, target='user', action='add')
def do_passhash(args): """ Uses bcrypt to hash a password. :param args: Parsed ArgumentParser args :type args: argparse.Namespace :returns: The hashed password :rtype: str """ import bcrypt if args.password is not None: pw = args.password elif args.file is not None: pw = args.file.read() else: import getpass pw = getpass.getpass() salt = bcrypt.gensalt(log_rounds=args.rounds) return bcrypt.hashpw(pw, salt)
def register(ctx, request): try: payload = request.json() nickname = payload['nickname'] mail = payload['mail'] password = payload['password'] except KeyError as e: raise HTTPBadRequest('{} is required'.format(e)) except Exception as e: raise HTTPBadRequest(e) user = User.query.filter(or_(User.nickname == nickname, User.mail == mail)).first() if user is not None: return jsonify(code=400, message='user exist') catalog = Catalog(name='notes') user = User(nickname=nickname, mail=mail, catalogs=[catalog], password=bcrypt.hashpw(password.encode(), bcrypt.gensalt())) db.session.add(user) try: db.session.commit() return jsonify(code=200) except Exception as e: logging.error(e) db.session.rollback() raise HTTPInternalServerError(e)
def check_user_existed_or_signup(user_info): try: return_msg = {} with UserDao() as userDao: is_existed = userDao.checkUserExisted(userName=user_info['user_name']) if is_existed: return_msg['flash'] = 'The name "{name}" has been used'.format(name=user_info['user_name']) return return_msg hashed_passwd = bcrypt.hashpw(user_info['user_password'].encode('utf-8'),bcrypt.gensalt()) with UserDao() as userdao: userdao.createNewUser(userName=user_info['user_name'],userPassword=hashed_passwd) return_msg['flash'] = 'User "{name}" create success!'.format(name=user_info['user_name']) return return_msg except: return_msg["error"] = "Fail to check whether user is existed or create new user" return return_msg #
def initKeys(self): # initialize keys k & kPrime # k used for PRF; kPrime used for Enc/Dec # return (k, kPrime) #hashed = bcrypt.hashpw(self.password, bcrypt.gensalt()) hashed = bcrypt.hashpw(self.password, self.salt) if(DEBUG > 1): print("len of k = %d" % len(hashed)) print("k = %s" % hashed) # Currently k and kPrime are equal # TODO: Sort out requirements of k and kPrime # Research uses both, but not sure the difference return (hashed, hashed)
def signUp(): # Get data from sign up form on front-end (in JSON format) custEntry = request.get_json() entered_password = custEntry['password'] entered_password2 = custEntry['password2'] if entered_password == entered_password2: # Encrypt the password entered by the user salt = bcrypt.gensalt() encrypted_password = bcrypt.hashpw(entered_password.encode('utf-8'), salt) # Store the user information as a new entry (with the encrypted_password) result = db.insert('customer', username=custEntry['username'], email=custEntry['email'], password=encrypted_password, first_name=custEntry['first_name'], last_name=custEntry['last_name']) # Returns the user entered information return jsonify(result) else: # If passwords don't match return 'login failed', 401 # Allows a user to login to the site
def post(self): if not "app_id" in request.json or not "app_secret" in request.json: error = { "code": "MISSING_APP_ID_OR_APP_SECRET" } return jsonify({'error': error}), 400 existing_app = App.objects.filter(app_id=request.json.get('app_id')).first() if existing_app: error = { "code": "APP_ID_ALREADY_EXISTS" } return jsonify({'error': error}), 400 else: # create the credentials salt = bcrypt.gensalt() hashed_password = bcrypt.hashpw(request.json.get('app_secret'), salt) app = App( app_id=request.json.get('app_id'), app_secret=hashed_password ).save() return jsonify({'result': 'ok'})
def post(self): if not self.check_unique_user(self.get_argument("parasite")): self.render2("create_user.html") if self.get_argument("password") == self.get_argument("password2"): hashed_password = yield executor.submit( bcrypt.hashpw, escape.utf8(self.get_argument("password")), bcrypt.gensalt()) parasite_id = self.db.execute( "INSERT INTO parasite (id, email, password, username) " "VALUES (%s, %s, %s, %s)", self.get_argument("parasite"), self.get_argument("email"), hashed_password, self.get_argument("parasite")) self.set_secure_cookie("parasite", str(parasite_id), expires_days=182) self.redirect(self.get_argument("next", "/")) else: self.render2("create_user.html", error="incorrect password")
def post(self): token = self.get_argument("token") try: from tornado_chat import SECRET_KEY serializer = URLSafeTimedSerializer(SECRET_KEY) parasite = serializer.loads(token, max_age=86400) # do i really have to do 24hrs in secs? parasiteId = self.db.get("SELECT id, reset_token FROM parasite WHERE id = %s", parasite) if parasiteId is not None and self.get_argument("password") == self.get_argument( "password2") and parasiteId.reset_token == token: hashed_password = yield executor.submit( bcrypt.hashpw, tornado.escape.utf8(self.get_argument("password")), bcrypt.gensalt()) self.db.execute("UPDATE parasite SET password = %s, reset_token='' WHERE id = %s", hashed_password, parasite) self.redirect("login?error=Password reset. Please login.") else: self.redirect("login?error=Password reset failed.") except: self.redirect("login?error=Password reset failed.")
def change_user_password(self, user, password_list): """ Update a user's password to the given value. Requires that the value be sent with a confirmation entry (two identical values) :param user: user with the password change :param password_list: list containing password and confirmation :return: for exiting if necessary information is not available """ if user != self.username or not password_list or len(password_list) != 2 or password_list[0] != password_list[ 1]: return updating_participants = get_matching_participants(self.participants, self.current_user['id']) hashed_password = yield executor.submit( bcrypt.hashpw, tornado.escape.utf8(password_list[0]), bcrypt.gensalt()) if self.current_user.password != hashed_password: self.http_server.db.execute("UPDATE parasite SET password = %s WHERE id = %s", hashed_password, self.current_user['id']) self.broadcast_from_server(updating_participants, 'PASSWORD CHANGED! I hope that\'s what you wanted.')
def signup(): if request.method=='POST': users = mongo.db.users api_list=[] existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]}) for i in existing_user: # print (str(i)) api_list.append(str(i)) # print (api_list) if api_list == []: users.insert({ "email": (request.form['email']).lower(), "id": random.randint(1,1000), "name": request.form['name'], "password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()), "username": request.form['username'] }) session['username'] = request.form['username'] return redirect(url_for('home')) return 'That user already exists' else : return render_template('signup.html')
def signup(): if request.method=='POST': users = mongo.db.users api_list=[] existing_user = users.find({'$or':[{"username":request.form['username']} ,{"email":request.form['email']}]}) for i in existing_user: # print (str(i)) api_list.append(str(i)) # print (api_list) if api_list == []: users.insert({ "email": request.form['email'], "id": random.randint(1,1000), "name": request.form['name'], "password": bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt()), "username": request.form['username'] }) session['username'] = request.form['username'] return redirect(url_for('home')) return 'That user already exists' else : return render_template('signup.html')
def register(): username = loggedIn(session, LoggedIn) if username != False: return render_template('index.html', username=username) form = RegisterForm() if form.validate_on_submit(): hashedPwd = hashpw(str(request.form['password']).encode('utf-8'), gensalt()) # encrypt user's password user = User(username=request.form['username'], password=hashedPwd) # create user db.session.add(user) db.session.commit() # save new user in User table new_user = User.query.filter_by(username=request.form['username']).first() # new profile user_profile = Profile(user_id=new_user.id, name="no-name", surname="no-surname", avatar="saitama-batman.jpg", description="no-description", skills="no-skills,") db.session.add(user_profile) db.session.commit() # save new profile in Profile table return render_template('registration_success.html', username=request.form['username']) return render_template('register.html', form=form)
def manage_users_add(): if request.method == 'POST': u = User() error = None u.name = request.form['username'].lower() if u.name is None: error = "Username not unique!" if request.form['password1'] == request.form['password2']: #u.password = request.form['password1'] u.password = bcrypt.hashpw(request.form['password1'], bcrypt.gensalt()) else: error = "Passwords do not match!" u.longname = request.form['longname'] u.email = request.form['email'] u.rfid_id = request.form['rfid_id'] if error is None: add_user(u) return render_template('manage_users_add.html', success="User created!", user=get_user_by_name(session.get('name'))); return render_template('manage_users_add.html', error=error, user=get_user_by_name(session.get('name'))) return render_template('manage_users_add.html', user=get_user_by_name(session.get('name')))
def reset_password(token): form = ResetForm() tokenemail = confirm_token(token) if tokenemail is False: flash('The confirmation link is invalid or has expired.', 'danger') return redirect(url_for('regular.home')) user = User.query.filter_by(email = tokenemail).first() if user: if request.method == 'POST': if form.validate_on_submit(): user.pw_hash = bcrypt.hashpw(form.password.data.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') db.session.commit() login_user(user,remember=True) flash('Your password has been reset.') return redirect(url_for('regular.home')) else: return render_template('reset.html', form=form, token=token) elif request.method == 'GET': return render_template('reset.html', form=form, token=token) else: flash('The confirmation link is invalid or has expired.', 'danger')
def startup(self): password = 'root' password = password.encode('utf-8') hashed = bcrypt.hashpw(password, bcrypt.gensalt()) root = await self.db.find_one({'user': ROLE_ROOT}) if root is None: root = await self.db.insert_one({ 'user': ROLE_ROOT, 'password': hashed, 'role': 'administrator', }) self.__root_id = str(root.inserted_id) else: self.__root_id = str(root['_id']) self.event.emit('user-add', { 'id': self.__root_id, 'user': 'root' }) await self.db.create_index('user')
def create_user(): if request.method == 'POST': username = request.form.get('username', None).strip() # Aa09_.- allowed password = request.form.get('password', None) role = request.form.get('role', 'Guest') if re.match(r'^[\w.-]+$', username) and password: # Form was completed with valid input matching_user = "SELECT user_pk FROM users WHERE username = %s;" user_does_exist = helpers.duplicate_check(matching_user, [username]) if user_does_exist: flash('Username already exists') else: salt = bcrypt.gensalt(12) password = bcrypt.hashpw(password.encode('utf-8'), bytes(salt)) new_user = ("INSERT INTO users (username, password, salt, role_fk) " "VALUES (%s, %s, %s, %s);") helpers.db_change(new_user, [username, password, salt, role]) flash('Your account was created!') else: flash('Please enter a username and password.') return render_template('create_user.html')
def hash_password(password): print(password, bcrypt.hashpw(password, bcrypt.gensalt()))
def hash_password(password): """ Hash plaintext password. Args: password: plaintext password Returns: Secure hash of password. """ return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(8))
def set_password(self, password): self.hashed_password = bcrypt.hashpw( password.encode("utf-8"), bcrypt.gensalt())
def hash_bcrypt(cls, password): if isinstance(password, unicode): password = password.encode('utf-8') hash_ = bcrypt.hashpw(password, bcrypt.gensalt()) return '$'.join(['bcrypt', hash_])
def hash_password(password): """ Hash plaintext password. Args: password: plaintext password Returns: Secure hash of password. """ return bcrypt.hashpw(password, bcrypt.gensalt(8))
def _bcrypt_hash_password(password): """Hashes and salts a given string using bcrypt. """ salt = bcrypt.gensalt() password_hash = bcrypt.hashpw(password, salt) return password_hash
def set_password(self, password): self.password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode('UTF-8')
def __init__(self, username, email, password): self.username = username self.email = email self.password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') # decoding to re-encode later to prevent bytestring confusion # in python3 self.active = False
def _hash_password(password: str): return bcrypt.hashpw( password.encode("utf-8"), bcrypt.gensalt() ).decode("utf-8")
def hash_password(password): """ Hash a password for the first time using bcrypt from pypi Add a randomly-generated salt """ return bcrypt.hashpw(password, bcrypt.gensalt())
def password(self, value): """ Ensure that passwords are always stored hashed and salted. Requirements: https://blog.codinghorror.com/password-rules-are-bullshit/ :param str value: New password for login """ if len(value) < 10: raise ValueError('Minimum password length is 10 characters.') if self.email and value.lower() == self.email.lower(): raise ValueError('Using email as password forbidden') if utilities.is_common_password(value): raise ValueError('Commong passwords are forbidden') # When a login is first created, give them a salt self._password = bcrypt.hashpw(value.encode('utf8'), bcrypt.gensalt())
def hashPassword(mapper, conneciton, target): state = inspect(target) hist = state.get_history("pwd", True) if hist.has_changes() and target.pwd: # Rounds fixed to 10 for PHP front-end compatibility target.pwd = bcrypt.hashpw(target.pwd.encode(sg.DEFAULT_CHARSET), bcrypt.gensalt(10))
def encrypt(password, salt=None): return bcrypt.hashpw(password.encode('utf-8'), salt if salt else bcrypt.gensalt())
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 set_password(self, password): self.password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(flask.current_app.config['BCRYPT_LOG_ROUNDS'])).decode('utf-8')
def hash(cls, plain): plain = cls.digest(plain) return bcrypt.hashpw(plain, bcrypt.gensalt(cls.HASH_LOG_ROUNDS))
def token_ttl(self, email): token = bcrypt.gensalt(24).encode('hex') key = self.keys.signup_token(email) expires = settings.API_TOKEN_EXPIRATION_TIME * 3 return self.connection.setex(key, expires, token)
def hashpw(password): digest = hashlib.sha256(password.encode()).digest() encoded = base64.b64encode(digest) return bcrypt.hashpw(encoded, bcrypt.gensalt())
def hash_pwd(p): if isinstance(p, str): p = p.encode('utf-8') return bcrypt.hashpw(p, bcrypt.gensalt()).decode('ascii')
def val_Reg(self, postData): status = True errorlist = [] if not NAME_REGEX.match(postData['first_name']): errorlist.append("Not a valid first name!") if len(postData['first_name']) < 2 or len(postData['last_name']) < 2: errorlist.append("Name must have at least 2 letters") status = False if not NAME_REGEX.match(postData['last_name']): errorlist.append("Not a valid last name") status = False if not EMAIL_REGEX.match(postData['email']): errorlist.append("Not a valid email") status = False if len(postData['password']) < 8: errorlist.append("Password must be at least 8 characters") status = False if postData['password'] != postData['confirm']: errorlist.append("Passwords do not match!") status = False if len(User.objects.filter(email=postData['email'])) > 0: errorlist.append("Email is already registered!") status = False if status == False: return {'errors': errorlist} else: password = postData['password'] hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()) user = User.objects.create(first_name=postData['first_name'], last_name=postData['last_name'], email=postData['email'], password=hashed) return {'register': user}
def add_default_user(conn): username = 'pydbvolve' salt = bcrypt.gensalt() hashpw = bcrypt.hashpw(salt, salt) sql = """ insert into users (id, username, hashpw, salt) values (?, ?, ?, ?); """ values = (1, username, hashpw, salt) with conn.cursor() as cur: cur.execute(sql, values) # End add_default_user