Python bcrypt.gensalt() Examples

The following are 30 code examples of bcrypt.gensalt(). 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: 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 #2
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 #3
Source File: blog.py    From trace-examples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def post(self):
        if await self.any_author_exists():
            raise tornado.web.HTTPError(400, "author already created")
        hashed_password = await tornado.ioloop.IOLoop.current().run_in_executor(
            None,
            bcrypt.hashpw,
            tornado.escape.utf8(self.get_argument("password")),
            bcrypt.gensalt(),
        )
        author = await self.queryone(
            "INSERT INTO authors (email, name, hashed_password) "
            "VALUES (%s, %s, %s) RETURNING id",
            self.get_argument("email"),
            self.get_argument("name"),
            tornado.escape.to_unicode(hashed_password),
        )
        self.set_secure_cookie("blogdemo_user", str(author.id))
        self.redirect(self.get_argument("next", "/")) 
Example #4
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 #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: insert_admin.py    From streamingbandit with MIT License 6 votes vote down vote up
def insert_admin():
    dirs = os.listdir()
    if 'app' in dirs:
        f = open("app/config.cfg", 'r')
    else:
        f = open("./config.cfg", 'r')
    settings = yaml.full_load(f)
    settings = settings['docker']
    mongo_client = MongoClient(settings['mongo_ip'], settings['mongo_port'])
    mongo_db = mongo_client['userinfo']
    userinfo = mongo_db['userinfo']
    f.close()

    parser = argparse.ArgumentParser(description = "Add admin user to MongoDB")
    parser.add_argument('-p', '--password', type = str, help = "Admin password", required = True)

    if userinfo.find({'username':'admin'}).count() > 0:
        print("Admin already exists")
    else:
        args = parser.parse_args()
        password = args.password
        hashed = hashpw(password.encode('utf-8'), gensalt())
        userinfo.insert_one({"username":"admin","password":hashed,"user_id":0})
        print("Successfully added an admin user with password {}!".format(password)) 
Example #7
Source File: users.py    From streamingbandit with MIT License 6 votes vote down vote up
def create_user(self, username, password):
        if self.userinfo.find({'username':username}).count() > 0:
            return False
        else:
            # Create user
            # Find user with highest user_id and increment
            highest_user_id = self.userinfo.find_one(filter={"user_id":{"$ne":"admin"}},sort=[("user_id",DESCENDING)])
            if highest_user_id is None:
                user_id = 1
            elif highest_user_id is 0:
                user_id = 1
            else:
                user_id = highest_user_id["user_id"] + 1
            # Hash password
            hashed = hashpw(password.encode('utf-8'), gensalt())
            # Set user
            self.userinfo.insert_one({"username":username,"password":hashed,"user_id":user_id})
            return user_id 
Example #8
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 #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: 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 #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: firstuseauthenticator.py    From firstuseauthenticator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def reset_password(self, username, new_password):
        """
        This allows changing the password of a logged user.
        """
        if not self._validate_password(new_password):
            login_err = (
                'Password too short! Please choose a password at least %d characters long.'
                % self.min_password_length
            )
            self.log.error(login_err)
            # Resetting the password will fail if the new password is too short.
            return login_err
        with dbm.open(self.dbm_path, 'c', 0o600) as db:
            db[username] = bcrypt.hashpw(new_password.encode(),
                                         bcrypt.gensalt())
        login_msg = "Your password has been changed successfully!"
        self.log.info(login_msg)
        return login_msg 
Example #13
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 #14
Source File: accounts.py    From sawtooth-marketplace with Apache License 2.0 5 votes vote down vote up
def _create_auth_dict(request, public_key, private_key):
    auth_entry = {
        'public_key': public_key,
        'email': request.json['email']
    }

    auth_entry['encrypted_private_key'] = common.encrypt_private_key(
        request.app.config.AES_KEY, public_key, private_key)
    auth_entry['hashed_password'] = bcrypt.hashpw(
        bytes(request.json.get('password'), 'utf-8'), bcrypt.gensalt())

    return auth_entry 
Example #15
Source File: test_base.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def client_post_login(self):
        self.user = User.objects.create_user(
            username=self.username, password=self.password
        )

        url = reverse("login")

        if (
            "callisto_core.accounts.auth.EncryptedBackend"
            in settings.AUTHENTICATION_BACKENDS
        ):
            from hashlib import sha256
            import bcrypt
            from callisto_core.accounts.auth import index

            userhash = sha256(self.username.lower().encode("utf-8")).hexdigest()
            usercrypt = bcrypt.hashpw(userhash.encode("utf-8"), bcrypt.gensalt())
            userindex = index(userhash)

            self.userhash = userhash

            Account.objects.create(
                user=self.user,
                site_id=1,
                encrypted_username=usercrypt.decode(),
                username_index=userindex,
            )

            data = {"username": self.userhash, "password": self.password}
        else:
            data = {"username": self.username, "password": self.password}
            Account.objects.create(user=self.user, site_id=1)
        response = self.client.post(url, data, follow=True)
        self.assertIn(response.status_code, self.valid_statuses)
        return response 
Example #16
Source File: models.py    From DemonHunter with MIT License 5 votes vote down vote up
def password(self, _password):
        self.password_hash = bcrypt.hashpw(_password.encode('utf8'),
            bcrypt.gensalt()).decode() 
Example #17
Source File: test_base.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def _setup_user(self):
        username = "testing_122"
        self.user = User.objects.create_user(username=username, password="testing_12")

        if (
            "callisto_core.accounts.auth.EncryptedBackend"
            in settings.AUTHENTICATION_BACKENDS
        ):
            from hashlib import sha256
            import bcrypt
            from callisto_core.accounts.auth import index

            userhash = sha256(username.lower().encode("utf-8")).hexdigest()
            usercrypt = bcrypt.hashpw(userhash.encode("utf-8"), bcrypt.gensalt())
            userindex = index(userhash)

            Account.objects.create(
                user=self.user,
                site_id=1,
                school_email=self.school_email,
                encrypted_username=usercrypt.decode(),
                username_index=userindex,
            )
            self.client.login(username=userhash, password="testing_12")
            self.userhash = userhash
        else:
            Account.objects.create(
                user=self.user, site_id=1, school_email=self.school_email
            )
            self.client.login(username=username, password="testing_12") 
Example #18
Source File: user.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def get_hashed_password(self, plain_text_password=None):
        # Hash a password for the first time
        #   (Using bcrypt, the salt is saved into the hash itself)
        if plain_text_password is None:
            return plain_text_password

        pw = plain_text_password if plain_text_password else self.plain_text_password
        return bcrypt.hashpw(pw.encode('utf-8'), bcrypt.gensalt()) 
Example #19
Source File: database.py    From od-database with MIT License 5 votes vote down vote up
def generate_login(self, username, password) -> None:

        with psycopg2.connect(self.db_conn_str) as conn:
            cursor = conn.cursor()

            hashed_pw = bcrypt.hashpw(password.encode(), bcrypt.gensalt(12))

            cursor.execute("INSERT INTO Admin (username, password, role) VALUES (%s,%s, 'admin')",
                           (username, hashed_pw))
            conn.commit() 
Example #20
Source File: Administrator.py    From PyRecognizer with MIT License 5 votes vote down vote up
def encrypt_password(plain_text_password: str) -> str:
        # Hash a password for the first time
        #   (Using bcrypt, the salt is saved into the hash itself)
        return bcrypt.hashpw(plain_text_password, bcrypt.gensalt()) 
Example #21
Source File: passwordHash.py    From graphql-over-kafka with MIT License 5 votes vote down vote up
def _new(password, rounds):
        """
            Returns a new bcrypt hash for the given password and rounds.
            note: Implemented to reduce repitition in `new` and `rehash`.
        """
        return bcrypt.hashpw(password, bcrypt.gensalt(rounds)) 
Example #22
Source File: accounts.py    From sawtooth-marketplace with Apache License 2.0 5 votes vote down vote up
def update_account_info(request):
    """Updates auth information for the authorized account"""
    token = common.deserialize_auth_token(
        request.app.config.SECRET_KEY, request.token)

    update = {}
    if request.json.get('password'):
        update['hashed_password'] = bcrypt.hashpw(
            bytes(request.json.get('password'), 'utf-8'), bcrypt.gensalt())
    if request.json.get('email'):
        update['email'] = request.json.get('email')

    if update:
        updated_auth_info = await auth_query.update_auth_info(
            request.app.config.DB_CONN,
            token.get('email'),
            token.get('public_key'),
            update)
        new_token = common.generate_auth_token(
            request.app.config.SECRET_KEY,
            updated_auth_info.get('email'),
            updated_auth_info.get('publicKey'))
    else:
        updated_auth_info = await accounts_query.fetch_account_resource(
            request.app.config.DB_CONN,
            token.get('public_key'),
            token.get('public_key'))
        new_token = request.token

    return response.json(
        {
            'authorization': new_token,
            'account': updated_auth_info
        }) 
Example #23
Source File: models.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def hash_password(password):
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(12)) 
Example #24
Source File: Role_Manager.py    From AIL-framework with GNU Affero General Public License v3.0 5 votes vote down vote up
def hashing_password(bytes_password):
    hashed = bcrypt.hashpw(bytes_password, bcrypt.gensalt())
    return hashed 
Example #25
Source File: firstuseauthenticator.py    From firstuseauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def authenticate(self, handler, data):
        username = data['username']

        if not self.create_users:
            if not self._user_exists(username):
                return None

        password = data['password']
        # Don't enforce password length requirement on existing users, since that can
        # lock users out of their hubs.
        if not self._validate_password(password) and not self._user_exists(username):
            handler.custom_login_error = (
                'Password too short! Please choose a password at least %d characters long.'
                % self.min_password_length
            )

            self.log.error(handler.custom_login_error)
            return None
        with dbm.open(self.dbm_path, 'c', 0o600) as db:
            stored_pw = db.get(username.encode(), None)
            if stored_pw is not None:
                if bcrypt.hashpw(password.encode(), stored_pw) != stored_pw:
                    return None
            else:
                db[username] = bcrypt.hashpw(password.encode(),
                                             bcrypt.gensalt())
        return username 
Example #26
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 #27
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 #28
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 #29
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()) 
Example #30
Source File: database.py    From Loki with MIT License 5 votes vote down vote up
def hash_password(self, password):
        return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())