def hash_bcrypt(cls, password):
if isinstance(password, unicode):
password = password.encode('utf-8')
hash_ = bcrypt.hashpw(password, bcrypt.gensalt())
return '$'.join(['bcrypt', hash_])
python类gensalt()的实例源码
def hash_password(password):
"""
Hash plaintext password.
Args:
password: plaintext password
Returns:
Secure hash of password.
"""
return bcrypt.hashpw(password, bcrypt.gensalt(8))
def hash_password(password):
"""
Hash plaintext password.
Args:
password: plaintext password
Returns:
Secure hash of password.
"""
return bcrypt.hashpw(password, bcrypt.gensalt(8))
def _bcrypt_hash_password(password):
"""Hashes and salts a given string using bcrypt.
"""
salt = bcrypt.gensalt()
password_hash = bcrypt.hashpw(password, salt)
return password_hash
def set_password(self, password):
self.password = bcrypt.hashpw(password.encode('UTF-8'), bcrypt.gensalt()).decode('UTF-8')
def hash_bcrypt(cls, password):
if isinstance(password, unicode):
password = password.encode('utf-8')
hash_ = bcrypt.hashpw(password, bcrypt.gensalt())
return '$'.join(['bcrypt', hash_])
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = bcrypt.hashpw(password.encode('utf-8'),
bcrypt.gensalt()).decode('utf-8')
# decoding to re-encode later to prevent bytestring confusion
# in python3
self.active = False
def _hash_password(password: str):
return bcrypt.hashpw(
password.encode("utf-8"),
bcrypt.gensalt()
).decode("utf-8")
def hash_password(password):
"""
Hash a password for the first time using bcrypt from pypi
Add a randomly-generated salt
"""
return bcrypt.hashpw(password, bcrypt.gensalt())
def password(self, value):
"""
Ensure that passwords are always stored hashed and salted.
Requirements: https://blog.codinghorror.com/password-rules-are-bullshit/
:param str value: New password for login
"""
if len(value) < 10:
raise ValueError('Minimum password length is 10 characters.')
if self.email and value.lower() == self.email.lower():
raise ValueError('Using email as password forbidden')
if utilities.is_common_password(value):
raise ValueError('Commong passwords are forbidden')
# When a login is first created, give them a salt
self._password = bcrypt.hashpw(value.encode('utf8'), bcrypt.gensalt())
def hashPassword(mapper, conneciton, target):
state = inspect(target)
hist = state.get_history("pwd", True)
if hist.has_changes() and target.pwd:
# Rounds fixed to 10 for PHP front-end compatibility
target.pwd = bcrypt.hashpw(target.pwd.encode(sg.DEFAULT_CHARSET), bcrypt.gensalt(10))
def encrypt(password, salt=None):
return bcrypt.hashpw(password.encode('utf-8'), salt if salt else bcrypt.gensalt())
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)
def set_password(self, password):
self.password = bcrypt.hashpw(password.encode('utf-8'),
bcrypt.gensalt(flask.current_app.config['BCRYPT_LOG_ROUNDS'])).decode('utf-8')
def hash(cls, plain):
plain = cls.digest(plain)
return bcrypt.hashpw(plain, bcrypt.gensalt(cls.HASH_LOG_ROUNDS))
def token_ttl(self, email):
token = bcrypt.gensalt(24).encode('hex')
key = self.keys.signup_token(email)
expires = settings.API_TOKEN_EXPIRATION_TIME * 3
return self.connection.setex(key, expires, token)
def hashpw(password):
digest = hashlib.sha256(password.encode()).digest()
encoded = base64.b64encode(digest)
return bcrypt.hashpw(encoded, bcrypt.gensalt())
def hash_pwd(p):
if isinstance(p, str):
p = p.encode('utf-8')
return bcrypt.hashpw(p, bcrypt.gensalt()).decode('ascii')
def val_Reg(self, postData):
status = True
errorlist = []
if not NAME_REGEX.match(postData['first_name']):
errorlist.append("Not a valid first name!")
if len(postData['first_name']) < 2 or len(postData['last_name']) < 2:
errorlist.append("Name must have at least 2 letters")
status = False
if not NAME_REGEX.match(postData['last_name']):
errorlist.append("Not a valid last name")
status = False
if not EMAIL_REGEX.match(postData['email']):
errorlist.append("Not a valid email")
status = False
if len(postData['password']) < 8:
errorlist.append("Password must be at least 8 characters")
status = False
if postData['password'] != postData['confirm']:
errorlist.append("Passwords do not match!")
status = False
if len(User.objects.filter(email=postData['email'])) > 0:
errorlist.append("Email is already registered!")
status = False
if status == False:
return {'errors': errorlist}
else:
password = postData['password']
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
user = User.objects.create(first_name=postData['first_name'], last_name=postData['last_name'], email=postData['email'], password=hashed)
return {'register': user}
def add_default_user(conn):
username = 'pydbvolve'
salt = bcrypt.gensalt()
hashpw = bcrypt.hashpw(salt, salt)
sql = """
insert into users (id, username, hashpw, salt) values (?, ?, ?, ?);
"""
values = (1, username, hashpw, salt)
with conn.cursor() as cur:
cur.execute(sql, values)
# End add_default_user