Python bcrypt.hashpw() Examples

The following are 30 code examples of bcrypt.hashpw(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bcrypt , or try the search function .
Example #1
Source File: app.py    From Cloud-Native-Python with MIT License 7 votes vote down vote up
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!' 
Example #2
Source File: migrate.py    From InfraBox with Apache License 2.0 6 votes vote down vote up
def configure_admin(conn):
    logger.info("Updating admin credentials")

    password = get_env('INFRABOX_ADMIN_PASSWORD')
    email = get_env('INFRABOX_ADMIN_EMAIL')

    hashed_password = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())

    cur = conn.cursor()
    cur.execute('''
        INSERT into "user" (id, username, name, email, password, role)
        VALUES ('00000000-0000-0000-0000-000000000000', 'Admin', 'Admin', %s, %s, 'admin')
        ON CONFLICT (id) DO UPDATE
        SET email = %s,
            password = %s
    ''', [email, hashed_password, email, hashed_password])
    cur.close()
    conn.commit() 
Example #3
Source File: generateconfig.py    From nukemyluks with Apache License 2.0 6 votes vote down vote up
def main():
    if len(sys.argv) < 2:
        usage()

    hashed_password = hashpw(sys.argv[1], gensalt(log_rounds=DEFAULT_ROUNDS))

    configparser = ConfigParser.ConfigParser()
    configparser.add_section('config')
    configparser.set('config', 'password_hash', hashed_password)
    
    try:
        config_file = open('config.ini', 'w')
        configparser.write(config_file)
    except Exception as err:
        print "[!] Error creating config file: %s" % err
        sys.exit()
        
    print "[+] Configuration file created successfully."
    config_file.close() 
Example #4
Source File: migrate.py    From infrabox with MIT License 6 votes vote down vote up
def configure_admin(conn):
    logger.info("Updating admin credentials")

    password = get_env('INFRABOX_ADMIN_PASSWORD')
    email = get_env('INFRABOX_ADMIN_EMAIL')

    hashed_password = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())

    cur = conn.cursor()
    cur.execute('''
        INSERT into "user" (id, username, name, email, password)
        VALUES ('00000000-0000-0000-0000-000000000000', 'Admin', 'Admin', %s, %s)
        ON CONFLICT (id) DO UPDATE
        SET email = %s,
            password = %s
    ''', [email, hashed_password, email, hashed_password])
    cur.close()
    conn.commit() 
Example #5
Source File: app.py    From Cloud-Native-Python with MIT License 6 votes vote down vote up
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') 
Example #6
Source File: info.py    From aerospike-admin with Apache License 2.0 6 votes vote down vote up
def _hashpassword(password):
    if hasbcrypt == False:
        print("Authentication failed: bcrypt not installed.")
        sys.exit(1)

    if password == None:
        password = ""

    if len(password) != 60 or password.startswith("$2a$") == False:
        password = bcrypt.hashpw(password, str_to_bytes("$2a$10$7EqJtq98hPqEX7fNZaFWoO"))

    return password

###############################


########### Security ########## 
Example #7
Source File: app.py    From Cloud-Native-Python with MIT License 6 votes vote down vote up
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') 
Example #8
Source File: app.py    From Cloud-Native-Python with MIT License 6 votes vote down vote up
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!' 
Example #9
Source File: app.py    From Cloud-Native-Python with MIT License 6 votes vote down vote up
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') 
Example #10
Source File: app.py    From Cloud-Native-Python with MIT License 6 votes vote down vote up
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!' 
Example #11
Source File: app.py    From Cloud-Native-Python with MIT License 6 votes vote down vote up
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') 
Example #12
Source File: utils.py    From contentdb with GNU General Public License v3.0 6 votes vote down vote up
def make_flask_user_password(plaintext_str):
	# http://passlib.readthedocs.io/en/stable/modular_crypt_format.html
	# http://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html#format-algorithm
	# Flask_User stores passwords in the Modular Crypt Format.
	# https://github.com/lingthio/Flask-User/blob/master/flask_user/user_manager__settings.py#L166
	#   Note that Flask_User allows customizing password algorithms.
	#   USER_PASSLIB_CRYPTCONTEXT_SCHEMES defaults to bcrypt but if
	#   default changes or is customized, the code below needs adapting.
	# Individual password values will look like:
	#   $2b$12$.az4S999Ztvy/wa3UdQvMOpcki1Qn6VYPXmEFMIdWQyYs7ULnH.JW
	#   $XX$RR$SSSSSSSSSSSSSSSSSSSSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
	# $XX : Selects algorithm (2b is bcrypt).
	# $RR : Selects bcrypt key expansion rounds (12 is 2**12 rounds).
	# $SSS... : 22 chars of (random, per-password) salt
	#  HHH... : 31 remaining chars of password hash (note no dollar sign)
	import bcrypt
	plaintext = plaintext_str.encode("UTF-8")
	password = bcrypt.hashpw(plaintext, bcrypt.gensalt())
	if isinstance(password, str):
		return password
	else:
		return password.decode("UTF-8") 
Example #13
Source File: app.py    From Cloud-Native-Python with MIT License 6 votes vote down vote up
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!' 
Example #14
Source File: app.py    From Cloud-Native-Python with MIT License 6 votes vote down vote up
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') 
Example #15
Source File: utils.py    From fence with Apache License 2.0 6 votes vote down vote up
def hash_secret(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        has_secret = "client_secret" in flask.request.form
        has_client_id = "client_id" in flask.request.form
        if flask.request.form and has_secret and has_client_id:
            form = flask.request.form.to_dict()
            with flask.current_app.db.session as session:
                client = (
                    session.query(Client)
                    .filter(Client.client_id == form["client_id"])
                    .first()
                )
                if client:
                    form["client_secret"] = bcrypt.hashpw(
                        form["client_secret"].encode("utf-8"),
                        client.client_secret.encode("utf-8"),
                    ).decode("utf-8")
                flask.request.form = ImmutableMultiDict(form)

        return f(*args, **kwargs)

    return wrapper 
Example #16
Source File: photobackup.py    From server-bottle with GNU General Public License v2.0 6 votes vote down vote up
def validate_password(request, isTest=False):
    """ Validates the password given in the request
        against the stored Bcrypted one. """
    password = None
    try:
        password = request.forms.get('password').encode('utf-8')
    except AttributeError:
        return end(403, "No password in request")

    if 'PasswordBcrypt' in config:
        passcrypt = config['PasswordBcrypt'].encode('utf-8')
        if bcrypt.hashpw(password, passcrypt) != passcrypt:
            return end(403, "wrong password!")
    elif 'Password' in config and config['Password'] != password:
        return end(403, "wrong password!")
    elif isTest:
        return end(401, "There's no password in server configuration!") 
Example #17
Source File: model.py    From polycul.es with MIT License 6 votes vote down vote up
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 
Example #18
Source File: __init__.py    From platypush with MIT License 5 votes vote down vote up
def _encrypt_password(pwd):
        return bcrypt.hashpw(pwd.encode(), bcrypt.gensalt(12)) 
Example #19
Source File: fields.py    From quay with Apache License 2.0 5 votes vote down vote up
def matches(self, value):
        """
        Returns true if this credential matches the unhashed value given.
        """
        return bcrypt.hashpw(value.encode("utf-8"), self.hashed) == self.hashed 
Example #20
Source File: app.py    From Cloud-Native-Python with MIT License 5 votes vote down vote up
def profile():
    if request.method=='POST':
        users = mongo.db.users
        api_list=[]
        existing_users = users.find({"username":session['username']})
        for i in existing_users:
            # print (str(i))
            api_list.append(str(i))
        user = {}
        print (api_list)
        if api_list != []:
            print (request.form['email'])
            user['email']=(request.form['email']).lower()
            user['name']= request.form['name']
            user['password']=bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt())
            users.update({'username':session['username']},{'$set': user} )
        else:
            return 'User not found!'
        return redirect(url_for('index'))
    if request.method=='GET':
        users = mongo.db.users
        user=[]
        print (session['username'])
        existing_user = users.find({"username":session['username']})
        for i in existing_user:
            user.append(i)
        return render_template('profile.html', name=user[0]['name'], username=user[0]['username'], password=user[0]['password'], email=user[0]['email']) 
Example #21
Source File: fields.py    From quay with Apache License 2.0 5 votes vote down vote up
def from_string(cls, string_value):
        """
        Returns a Credential object from an unhashed string value.
        """
        return Credential(bcrypt.hashpw(string_value.encode("utf-8"), bcrypt.gensalt())) 
Example #22
Source File: model.py    From polycul.es with MIT License 5 votes vote down vote up
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) 
Example #23
Source File: conftest.py    From fence with Apache License 2.0 5 votes vote down vote up
def oauth_client(app, db_session, oauth_user):
    """
    Create a confidential OAuth2 client and add it to the database along with a
    test user for the client.
    """
    url = "https://oauth-test-client.net"
    client_id = "test-client"
    client_secret = fence.utils.random_str(50)
    hashed_secret = bcrypt.hashpw(
        client_secret.encode("utf-8"), bcrypt.gensalt()
    ).decode("utf-8")
    test_user = db_session.query(models.User).filter_by(id=oauth_user.user_id).first()
    db_session.add(
        models.Client(
            client_id=client_id,
            client_secret=hashed_secret,
            user=test_user,
            allowed_scopes=["openid", "user", "fence"],
            redirect_uris=[url],
            description="",
            is_confidential=True,
            name="testclient",
            grant_types=["authorization_code", "refresh_token"],
        )
    )
    db_session.commit()
    return Dict(client_id=client_id, client_secret=client_secret, url=url) 
Example #24
Source File: models.py    From fence with Apache License 2.0 5 votes vote down vote up
def check_client_secret(self, client_secret):
        check_hash = bcrypt.hashpw(
            client_secret.encode("utf-8"), self.client_secret.encode("utf-8")
        ).decode("utf-8")
        return check_hash == self.client_secret 
Example #25
Source File: user.py    From quay with Apache License 2.0 5 votes vote down vote up
def hash_password(password, salt=None):
    salt = salt or bcrypt.gensalt()
    salt = Bytes.for_string_or_unicode(salt).as_encoded_str()
    return bcrypt.hashpw(password.encode("utf-8"), salt) 
Example #26
Source File: endpoints.py    From fence with Apache License 2.0 5 votes vote down vote up
def validate_authenticate_client(self):
        """
        Override parent method for client validation.
        """
        client_params = self.parse_basic_auth_header()
        if not client_params:
            logger.debug(
                "validating client in revoke request:" " missing client auth header"
            )
            raise InvalidClientError(uri=self.uri)

        client_id, client_secret = client_params
        client = self.client_model.get_by_client_id(client_id)
        if not client:
            logger.debug(
                "validating client in revoke request:"
                " no client with matching client id:" + " " + client_id
            )
            raise InvalidClientError(uri=self.uri)

        # The stored client secret is hashed, so hash the secret from basic
        # authorization header to check against stored hash.
        hashed = client.client_secret
        if (
            bcrypt.hashpw(client_secret.encode("utf-8"), hashed.encode("utf-8")).decode(
                "utf-8"
            )
            != hashed
        ):
            logger.debug("client secret hash does not match stored secret hash")
            raise InvalidClientError(uri=self.uri)

        self._client = client 
Example #27
Source File: models.py    From wordai with MIT License 5 votes vote down vote up
def password(self, passwd):
        passwd = passwd.encode()
        salt = bcrypt.gensalt()
        self.encrypted_password = bcrypt.hashpw(passwd, salt).decode() 
Example #28
Source File: test_app.py    From ambassador-auth-httpbasic with Apache License 2.0 5 votes vote down vote up
def create_hashed_password(password):
    import bcrypt

    prepared_password = b64encode(sha256(password.encode("UTF-8")).hexdigest().encode("UTF-8"))
    return bcrypt.hashpw(prepared_password, bcrypt.gensalt()).decode("utf-8") 
Example #29
Source File: models.py    From wordai with MIT License 5 votes vote down vote up
def check_password(self, passwd):
        passwd = passwd.encode()
        if (not self.encrypted_password) or (not self.salt):
            return False
        # hashed = bcrypt.hashpw(passwd, self.salt)
        return bcrypt.checkpw(passwd, self.encrypted_password.encode()) 
Example #30
Source File: models.py    From tildemush with GNU General Public License v3.0 5 votes vote down vote up
def _hash_password(self):
        self.password = bcrypt.hashpw(self.password.encode('utf-8'), bcrypt.gensalt())