本文整理匯總了Python中bcrypt.gensalt方法的典型用法代碼示例。如果您正苦於以下問題:Python bcrypt.gensalt方法的具體用法?Python bcrypt.gensalt怎麽用?Python bcrypt.gensalt使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類bcrypt
的用法示例。
在下文中一共展示了bcrypt.gensalt方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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()
示例2: make_flask_user_password
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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")
示例3: configure_admin
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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()
示例4: save
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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
示例5: signup
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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')
示例6: signup
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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')
示例7: configure_admin
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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()
示例8: reset_password
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [as 別名]
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
示例9: post
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [as 別名]
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", "/"))
示例10: create_user
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [as 別名]
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
示例11: insert_admin
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [as 別名]
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))
示例12: post
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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", "/"))
示例13: set_password
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [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
示例14: __init__
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [as 別名]
def __init__(self, iterations=12, *args, **kwargs):
if None in (hashpw, gensalt):
raise ValueError('Missing library required for PasswordField: bcrypt')
self.bcrypt_iterations = iterations
self.raw_password = None
super(PasswordField, self).__init__(*args, **kwargs)
示例15: db_value
# 需要導入模塊: import bcrypt [as 別名]
# 或者: from bcrypt import gensalt [as 別名]
def db_value(self, value):
"""Convert the python value for storage in the database."""
if isinstance(value, unicode_type):
value = value.encode('utf-8')
salt = gensalt(self.bcrypt_iterations)
return value if value is None else hashpw(value, salt)