當前位置: 首頁>>代碼示例>>Python>>正文


Python bcrypt.hashpw方法代碼示例

本文整理匯總了Python中bcrypt.hashpw方法的典型用法代碼示例。如果您正苦於以下問題:Python bcrypt.hashpw方法的具體用法?Python bcrypt.hashpw怎麽用?Python bcrypt.hashpw使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在bcrypt的用法示例。


在下文中一共展示了bcrypt.hashpw方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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() 
開發者ID:juliocesarfort,項目名稱:nukemyluks,代碼行數:21,代碼來源:generateconfig.py

示例2: _hashpassword

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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 ########## 
開發者ID:aerospike,項目名稱:aerospike-admin,代碼行數:19,代碼來源:info.py

示例3: make_flask_user_password

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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") 
開發者ID:minetest,項目名稱:contentdb,代碼行數:24,代碼來源:utils.py

示例4: configure_admin

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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() 
開發者ID:SAP,項目名稱:InfraBox,代碼行數:20,代碼來源:migrate.py

示例5: save

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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 
開發者ID:makyo,項目名稱:polycul.es,代碼行數:21,代碼來源:model.py

示例6: validate_password

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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!") 
開發者ID:PhotoBackup,項目名稱:server-bottle,代碼行數:19,代碼來源:photobackup.py

示例7: hash_secret

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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 
開發者ID:uc-cdis,項目名稱:fence,代碼行數:25,代碼來源:utils.py

示例8: do_admin_login

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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!' 
開發者ID:PacktPublishing,項目名稱:Cloud-Native-Python,代碼行數:19,代碼來源:app.py

示例9: signup

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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') 
開發者ID:PacktPublishing,項目名稱:Cloud-Native-Python,代碼行數:26,代碼來源:app.py

示例10: do_admin_login

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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!' 
開發者ID:PacktPublishing,項目名稱:Cloud-Native-Python,代碼行數:19,代碼來源:app.py

示例11: signup

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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') 
開發者ID:PacktPublishing,項目名稱:Cloud-Native-Python,代碼行數:26,代碼來源:app.py

示例12: configure_admin

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
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() 
開發者ID:InfraBox,項目名稱:infrabox,代碼行數:20,代碼來源:migrate.py

示例13: post

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
def post(self):
        if self.any_author_exists():
            raise tornado.web.HTTPError(400, "author already created")
        hashed_password = yield executor.submit(
            bcrypt.hashpw, tornado.escape.utf8(self.get_argument("password")),
            bcrypt.gensalt())
        author_id = self.db.execute(
            "INSERT INTO authors (email, name, hashed_password) "
            "VALUES (%s, %s, %s)",
            self.get_argument("email"), self.get_argument("name"),
            hashed_password)
        self.set_secure_cookie("blogdemo_user", str(author_id))
        self.redirect(self.get_argument("next", "/")) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:15,代碼來源:blog.py

示例14: set_password

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
def set_password(self, password):
        salt = bcrypt.gensalt()
        password_hash = bcrypt.hashpw(password.encode(), salt).decode()
        self.salt = salt.decode()
        self.password = password_hash 
開發者ID:simple-login,項目名稱:app,代碼行數:7,代碼來源:models.py

示例15: check_password

# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import hashpw [as 別名]
def check_password(self, password) -> bool:
        if not self.password:
            return False
        password_hash = bcrypt.hashpw(password.encode(), self.salt.encode())
        return self.password.encode() == password_hash 
開發者ID:simple-login,項目名稱:app,代碼行數:7,代碼來源:models.py


注:本文中的bcrypt.hashpw方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。