python类hashpw()的实例源码

app.py 文件源码 项目:Cloud-Native-Python 作者: PacktPublishing 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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')
app.py 文件源码 项目:Cloud-Native-Python 作者: PacktPublishing 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def do_admin_login():
    users = mongo.db.users
    api_list=[]
    login_user = users.find({'username': request.form['username']})
    for i in login_user:
        api_list.append(i)
    print (api_list)
    if api_list != []:
        #print (api_list[0]['password'].decode('utf-8'), bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'))
        if api_list[0]['password'].decode('utf-8') == bcrypt.hashpw(request.form['password'].encode('utf-8'), api_list[0]['password']).decode('utf-8'):
            session['logged_in'] = api_list[0]['username']
            return redirect(url_for('index'))
        return 'Invalide username/password!'
    else:
        flash("Invalid Authentication")

    return 'Invalid User!'
app.py 文件源码 项目:Cloud-Native-Python 作者: PacktPublishing 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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')
app.py 文件源码 项目:Cloud-Native-Python 作者: PacktPublishing 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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')
models.py 文件源码 项目:TalkToMe 作者: glenjantz 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def login(self, postData):
        status = True
        errorlist = []
        user = User.objects.filter(username = postData['username'])
        if len(postData['username']) < 1:
            errorlist.append('Must fill in Username!')
            status = False
        if len(postData['password']) < 1:
            errorlist.append('Must fill in Password!')
            status = False
        else:
            if len(user) < 1:
                errorlist.append('Username not registered!')
                status = False
        if status == False:
            return {'errors': errorlist}
        else:
            if bcrypt.hashpw(postData['password'].encode(), user[0].password.encode()) == user[0].password:
                return {'login': True}
            else:
                status = False
                errorlist.append('Password does not match username!')
                return {'errors': errorlist}
test_handlers_bcrypt.py 文件源码 项目:enkiWS 作者: juliettef 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def fuzz_verifier_pybcrypt(self):
        # test against py-bcrypt, if available
        from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2X, IDENT_2Y
        from passlib.utils import to_native_str
        try:
            import bcrypt
        except ImportError:
            return
        if hasattr(bcrypt, "_ffi"):
            return
        def check_pybcrypt(secret, hash):
            "pybcrypt"
            secret = to_native_str(secret, self.fuzz_password_encoding)
            if hash.startswith(IDENT_2Y):
                hash = IDENT_2A + hash[4:]
            try:
                return bcrypt.hashpw(secret, hash) == hash
            except ValueError:
                raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
        return check_pybcrypt
bcrypt.py 文件源码 项目:enkiWS 作者: juliettef 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _calc_checksum_bcrypt(self, secret):
        # bcrypt behavior:
        #   hash must be ascii bytes
        #   secret must be bytes
        #   returns bytes
        if self.ident == IDENT_2:
            # bcrypt doesn't support $2$ hashes; but we can fake $2$ behavior
            # using the $2a$ algorithm, by repeating the password until
            # it's at least 72 chars in length.
            if secret:
                secret = repeat_string(secret, 72)
            config = self._get_config(IDENT_2A)
        else:
            config = self._get_config()
        if isinstance(config, unicode):
            config = config.encode("ascii")
        hash = _bcrypt.hashpw(secret, config)
        assert hash.startswith(config) and len(hash) == len(config)+31
        assert isinstance(hash, bytes)
        return hash[-31:].decode("ascii")
views.py 文件源码 项目:Pycourses 作者: billz96 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:baroness 作者: ulrichknecht 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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')))
test_handlers_bcrypt.py 文件源码 项目:python-flask-security 作者: weinbergdavid 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def fuzz_verifier_pybcrypt(self):
        # test against py-bcrypt, if available
        from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2B, IDENT_2X, IDENT_2Y, _detect_pybcrypt
        from passlib.utils import to_native_str
        try:
            import bcrypt
        except ImportError:
            return
        if not _detect_pybcrypt():
            return
        def check_pybcrypt(secret, hash):
            """pybcrypt"""
            secret = to_native_str(secret, self.fuzz_password_encoding)
            if len(secret) > 200:  # vulnerable to wraparound bug
                secret = secret[:200]
            if hash.startswith((IDENT_2B, IDENT_2Y)):
                hash = IDENT_2A + hash[4:]
            try:
                return bcrypt.hashpw(secret, hash) == hash
            except ValueError:
                raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
        return check_pybcrypt
regular.py 文件源码 项目:PhoenixNow 作者: ECGHelloWorld 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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')
server.py 文件源码 项目:planty 作者: agnaite 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def process_login():
    """Processes user input and either logs user in if input is in database"""

    # gets the user input from the username field and looks it up in the database
    username = request.form.get('username')
    user = User.query.filter_by(username=username).first()

    # if username entered exists in db, gets the password entered and compares
    # it to the one in the database
    if user:
        # if password is correct, adds user to the current session and redirects to home page
        if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user.password.encode('utf-8')).decode() == user.password:
            session['logged_in'] = user.user_id
            print 'logged in'
            return jsonify(session)
        # if password is incorrect, redirects to login page
        else:
            return 'error'
    # if username is not in the database, redirects to the registration form
    else:
        return 'error'
server.py 文件源码 项目:planty 作者: agnaite 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def update_user():
    """Saves updated user info."""

    user_id = request.form.get('id')
    user_to_update = User.query.get(int(user_id))

    if bcrypt.hashpw(request.form.get('password').encode('utf-8'), user_to_update.password.encode('utf-8')).decode() == user_to_update.password:
        if request.form.get('email'):
            user_to_update.email = request.form.get('email')
        if request.form.get('phone'):
            user_to_update.phone = request.form.get('phone')
    else:
        return "bad password"

    db.session.commit()

    return "ok"


# PlantUser Routes *********************************
handlers.py 文件源码 项目:IotCenter 作者: panjanek 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def post(self):
        username = tornado.escape.xhtml_escape(self.get_argument("username", ""))
        password = tornado.escape.xhtml_escape(self.get_argument("password", "")).encode('utf-8')   
        returnUrl = self.get_argument("returnUrl", "/")
        self.logger.info("login request with username={0} from ip={1}".format(username, self.request.remote_ip))
        if username == "admin" and bcrypt.hashpw(password, self.adminPasswordHash) == self.adminPasswordHash:
            self.set_secure_cookie("user", username, expires_days=1)
            self.redirect(returnUrl)
        else:
            self.logger.warning("Invalid login/password request with username={0} from ip={1}".format(username, self.request.remote_ip))
            self.render("views/login.html", errormsg="Invalid username or password.", returnUrl=returnUrl)
password_hashing.py 文件源码 项目:python-seminar-4 作者: babjo 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def hash_password(password):
    print(password, bcrypt.hashpw(password, bcrypt.gensalt()))
auth.py 文件源码 项目:picoCTF 作者: picoCTF 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def confirm_password(attempt, password_hash):
    """
    Verifies the password attempt

    Args:
        attempt: the password attempt
        password_hash: the real password pash
    """
    return bcrypt.hashpw(attempt.encode('utf-8'), password_hash) == password_hash
user.py 文件源码 项目:picoCTF 作者: picoCTF 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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))


问题


面经


文章

微信
公众号

扫码关注公众号