def login(self, userInput):
# errorList - Keeps tracks of all errors with the validation.
errorList = []
mail=userInput['check_email']
# Checks if the email and password don't match.
if not mail and not userInput['password']:
errorList.append('Unsuccessful login. Please fill in the email and password field!\n')
return False, errorList
# Check if user is in User table
print "*************"
print mail
if self.filter(email = mail) :
hashed = self.get(email = mail).password.encode()
password = userInput['check_password'].encode()
# Checks if the password is the correct one to the hashed one.
if bcrypt.hashpw(password, hashed) == hashed:
return True, self.get(email=mail)
else:
errorList.append('Unsuccessful login. Incorrect password!\n')
else:
errorList.append('Unsuccessful login. Your email is incorrect!\n')
return False, errorList
python类hashpw()的实例源码
def auth_update_cache(self):
if '' in self.ctx.cache_db: # Cache disabled?
return
key = self.username + ':' + self.domain
now = self.now # For tests
snow = str(now)
try:
salt = bcrypt.gensalt(rounds=self.ctx.bcrypt_rounds)
except TypeError:
# Old versions of bcrypt() apparently do not support the rounds option
salt = bcrypt.gensalt()
pwhash = bcrypt.hashpw(self.password, salt)
if key in self.ctx.cache_db:
(ignored, ts1, tsv, tsa, rest) = self.ctx.cache_db[key].split("\t", 4)
self.ctx.cache_db[key] = "\t".join((pwhash, ts1, snow, snow, rest))
else:
self.ctx.cache_db[key] = "\t".join((pwhash, snow, snow, snow, ''))
self.try_db_sync()
def _calc_checksum(self, secret):
# bcrypt behavior:
# secret must be bytes
# config must be ascii bytes
# returns ascii bytes
secret, ident = self._prepare_digest_args(secret)
config = self._get_config(ident)
if isinstance(config, unicode):
config = config.encode("ascii")
hash = _bcrypt.hashpw(secret, config)
assert hash.startswith(config) and len(hash) == len(config)+31, \
"config mismatch: %r => %r" % (config, hash)
assert isinstance(hash, bytes)
return hash[-31:].decode("ascii")
#-----------------------------------------------------------------------
# bcryptor backend
#-----------------------------------------------------------------------
def __setattr__(self, name, value):
"""
Overide __setattr__ to update dict value and field value at once
"""
object.__setattr__(self, name, value)
if name in self.dictValues: # If updating a field value
if self._meta.fields[name].salt: # field is salt
# If field is already salt do nothing.
# XXX Could create a security issue. What happend is value
# starts with $2b$ but it's not encrypted. Not critical for now
if not ("$2b$" in value and value[:4] == "$2b$"):
value = bcrypt.hashpw(value.encode('utf8'), bcrypt.gensalt())
object.__setattr__(self, name, value)
# If value is an instance of model class and has a relation.
# Append it to the corresponding field list
if hasattr(value, "_meta") and self.isForeignKey(self._meta.fields[name]):
self.dictValues[name] = getattr(value, self._meta.fields[name].reference.name)
return
self.dictValues[name] = value
def register(request):
check = User.objects.validateUser(request.POST)
if request.method != 'POST':
return redirect('/')
if check[0] == False:
for error in check[1]:
messages.add_message(request, messages.INFO, error, extra_tags="registration")
return redirect('/')
if check[0] == True:
#has password
hashed_pw = bcrypt.hashpw(request.POST.get('password').encode(), bcrypt.gensalt())
#create user
user = User.objects.create(
first_name = request.POST.get('first_name'),
last_name = request.POST.get('last_name'),
email = request.POST.get('email'),
password = hashed_pw,
)
#add user to session, logging them in
request.session['user_id'] = user.id
#route to user profile page
return redirect('/user')
def signup(self, postData):
errors = []
response = {}
#Validate form data
if not EMAIL_REGEX.match(postData['email']):
error.append('Email error')
if postData['password'] != postData['confirm_password']:
errors.append('Confirm password did not match.')
elif not PASSWORD_REGEX.match(postData['password']):
errors.append('Password must blah.')
#Compile errors and send to response messages
if errors:
response['status'] = False
response['errors'] = errors
else:
response['status'] = True
response['user'] = self.create(
email=postData['email'],
first_name=postData['first_name'],
last_name=postData['last_name'],
password=bcrypt.hashpw(postData['password'].encode('utf-8'),bcrypt.gensalt())
)
return response
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
def register_submit():
# first, check to see if the username already exists. SELECT statement.
check_username_query = "SELECT * FROM user where username = '%s'" % request.form['username']
cursor.execute(check_username_query)
check_username_result = cursor.fetchone()
# second, if it't not taken, then insert the username into mysql
if (check_username_result is None):
# no match. insert
session['username'] = request.form['username']
real_name = request.form['real_name']
username = request.form['username']
password = request.form['password'].encode('utf-8')
hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
email = request.form['email']
username_insert_query = "INSERT INTO user VALUES (DEFAULT, %s, %s, %s, %s, NULL)"
cursor.execute(username_insert_query, (real_name, username, hashed_password, email))
conn.commit()
return render_template('index.html')
else:
# second b, if it is taken, send them back to the register page with a message
return redirect('/register?username=taken')
def register_submit():
# first, check to see if the username already exists. SELECT statement.
check_username_query = "SELECT * FROM user where username = '%s'" % request.form['username']
cursor.execute(check_username_query)
check_username_result = cursor.fetchone()
# second, if it't not taken, then insert the username into mysql
if (check_username_result is None):
# no match. insert
session['username'] = request.form['username']
real_name = request.form['real_name']
username = request.form['username']
password = request.form['password'].encode('utf-8')
hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())
email = request.form['email']
username_insert_query = "INSERT INTO user VALUES (DEFAULT, %s, %s, %s, %s, NULL)"
cursor.execute(username_insert_query, (real_name, username, hashed_password, email))
conn.commit()
get_id_query = "SELECT id FROM user where username = '%s'" % request.form['username']
cursor.execute(get_id_query)
get_id_result = cursor.fetchone()
session['id'] = get_id_result[0]
return render_template('index.html')
else:
# second b, if it is taken, send them back to the register page with a message
return redirect('/register?username=taken')
def val_Login(self, postData):
user = User.objects.filter(email=postData['email'])
status = True
errorlist = []
if len(postData['email']) < 1 or len(postData['password']) < 1 :
errorlist.append("Please enter valid email and password")
return {'errors': errorlist}
if not EMAIL_REGEX.match(postData['email']):
errorlist.append("Not a valid email")
return {'errors': errorlist}
if len(user) < 1:
errorlist.append("You need to register first")
status = False
if status == False:
return {'errors': errorlist}
else:
if bcrypt.hashpw(postData['password'].encode(), user[0].password.encode()) == user[0].password:
return {'register': user[0]}
else:
errorlist.append("Incorrect Password")
return {'errors': errorlist}
def create_user_table(conn):
create_sql = """
create table users
(
id int primary key,
username text not null,
hashpw text not null,
salt text not null,
last_login_ts timestamp
);
"""
index_sql = """
create index ix01_users on users(username);
"""
with conn.cursor() as cur:
cur.execute(create_sql)
cur.execute(index_sql)
# End create_user_table
def add_user():
form = ctforge.forms.UserForm()
if request.method == 'POST':
if form.validate_on_submit():
query_handler((
'INSERT INTO users (team_id, name, surname, mail, '
' password, admin, hidden) '
'VALUES (%s, %s, %s, %s, %s, %s, %s)'),
(form.team_id.data, form.name.data,
form.surname.data, form.mail.data,
bcrypt.hashpw(form.password.data, bcrypt.gensalt()),
form.admin.data, form.hidden.data))
else:
flash_errors(form)
return redirect(url_for('admin', tab='users'))
return render_template('admin/data.html', form=form, target='user',
action='add')
def do_passhash(args):
"""
Uses bcrypt to hash a password.
:param args: Parsed ArgumentParser args
:type args: argparse.Namespace
:returns: The hashed password
:rtype: str
"""
import bcrypt
if args.password is not None:
pw = args.password
elif args.file is not None:
pw = args.file.read()
else:
import getpass
pw = getpass.getpass()
salt = bcrypt.gensalt(log_rounds=args.rounds)
return bcrypt.hashpw(pw, salt)
def register(ctx, request):
try:
payload = request.json()
nickname = payload['nickname']
mail = payload['mail']
password = payload['password']
except KeyError as e:
raise HTTPBadRequest('{} is required'.format(e))
except Exception as e:
raise HTTPBadRequest(e)
user = User.query.filter(or_(User.nickname == nickname, User.mail == mail)).first()
if user is not None:
return jsonify(code=400, message='user exist')
catalog = Catalog(name='notes')
user = User(nickname=nickname, mail=mail, catalogs=[catalog],
password=bcrypt.hashpw(password.encode(), bcrypt.gensalt()))
db.session.add(user)
try:
db.session.commit()
return jsonify(code=200)
except Exception as e:
logging.error(e)
db.session.rollback()
raise HTTPInternalServerError(e)
def fuzz_verifier_pybcrypt(self):
# test against py-bcrypt, if available
from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2X, IDENT_2Y
from passlib.utils import to_native_str
try:
import bcrypt
except ImportError:
return
if hasattr(bcrypt, "_ffi"):
return
def check_pybcrypt(secret, hash):
"pybcrypt"
secret = to_native_str(secret, self.fuzz_password_encoding)
if hash.startswith(IDENT_2Y):
hash = IDENT_2A + hash[4:]
try:
return bcrypt.hashpw(secret, hash) == hash
except ValueError:
raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
return check_pybcrypt
def _calc_checksum_bcrypt(self, secret):
# bcrypt behavior:
# hash must be ascii bytes
# secret must be bytes
# returns bytes
if self.ident == IDENT_2:
# bcrypt doesn't support $2$ hashes; but we can fake $2$ behavior
# using the $2a$ algorithm, by repeating the password until
# it's at least 72 chars in length.
if secret:
secret = repeat_string(secret, 72)
config = self._get_config(IDENT_2A)
else:
config = self._get_config()
if isinstance(config, unicode):
config = config.encode("ascii")
hash = _bcrypt.hashpw(secret, config)
assert hash.startswith(config) and len(hash) == len(config)+31
assert isinstance(hash, bytes)
return hash[-31:].decode("ascii")
def check_user_existed_or_signup(user_info):
try:
return_msg = {}
with UserDao() as userDao:
is_existed = userDao.checkUserExisted(userName=user_info['user_name'])
if is_existed:
return_msg['flash'] = 'The name "{name}" has been used'.format(name=user_info['user_name'])
return return_msg
hashed_passwd = bcrypt.hashpw(user_info['user_password'].encode('utf-8'),bcrypt.gensalt())
with UserDao() as userdao:
userdao.createNewUser(userName=user_info['user_name'],userPassword=hashed_passwd)
return_msg['flash'] = 'User "{name}" create success!'.format(name=user_info['user_name'])
return return_msg
except:
return_msg["error"] = "Fail to check whether user is existed or create new user"
return return_msg
#
def _authenticate(self, data):
namespace = manager.get_namespace(data['namespace'])
collection = namespace.get_collection(data['collection'])
if not UserPlugin.is_enabled(collection):
raise exceptions.PluginNotEnabled(UserPlugin.NAME)
if not (
collection.schema
and 'password' in collection.schema._schema.get('required', [])
and collection.schema._schema['properties']['password'] == self.PASSWORD_SCHEMA
):
raise exceptions.BadRequest(title='Bad password schema', detail='The schema for password must be {} and must be a required field'.format(self.PASSWORD_SCHEMA))
# TODO validate retrieved document
doc = collection.read(data['username'])
password = doc.data['password'].encode()
hashed = await asyncio.get_event_loop().run_in_executor(None, lambda: bcrypt.hashpw(data['password'].encode(), password))
if hashed == password:
return SelfAuthProvider.type, '{}:{}'.format(namespace.ref, collection.ref), data['username'], 8
raise exceptions.Unauthorized()
sse_client.py 文件源码
项目:Searchable-Symmetric-Encryption
作者: IanVanHoudt
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def initKeys(self):
# initialize keys k & kPrime
# k used for PRF; kPrime used for Enc/Dec
# return (k, kPrime)
#hashed = bcrypt.hashpw(self.password, bcrypt.gensalt())
hashed = bcrypt.hashpw(self.password, self.salt)
if(DEBUG > 1):
print("len of k = %d" % len(hashed))
print("k = %s" % hashed)
# Currently k and kPrime are equal
# TODO: Sort out requirements of k and kPrime
# Research uses both, but not sure the difference
return (hashed, hashed)
def signUp():
# Get data from sign up form on front-end (in JSON format)
custEntry = request.get_json()
entered_password = custEntry['password']
entered_password2 = custEntry['password2']
if entered_password == entered_password2:
# Encrypt the password entered by the user
salt = bcrypt.gensalt()
encrypted_password = bcrypt.hashpw(entered_password.encode('utf-8'), salt)
# Store the user information as a new entry (with the encrypted_password)
result = db.insert('customer', username=custEntry['username'], email=custEntry['email'], password=encrypted_password, first_name=custEntry['first_name'], last_name=custEntry['last_name'])
# Returns the user entered information
return jsonify(result)
else:
# If passwords don't match
return 'login failed', 401
# Allows a user to login to the site
def post(self):
if not "app_id" in request.json or not "app_secret" in request.json:
error = {
"code": "MISSING_APP_ID_OR_APP_SECRET"
}
return jsonify({'error': error}), 400
existing_app = App.objects.filter(app_id=request.json.get('app_id')).first()
if existing_app:
error = {
"code": "APP_ID_ALREADY_EXISTS"
}
return jsonify({'error': error}), 400
else:
# create the credentials
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(request.json.get('app_secret'), salt)
app = App(
app_id=request.json.get('app_id'),
app_secret=hashed_password
).save()
return jsonify({'result': 'ok'})
def fuzz_verifier_pybcrypt(self):
# test against py-bcrypt, if available
from passlib.handlers.bcrypt import IDENT_2, IDENT_2A, IDENT_2B, IDENT_2X, IDENT_2Y, _detect_pybcrypt
from passlib.utils import to_native_str
try:
import bcrypt
except ImportError:
return
if not _detect_pybcrypt():
return
def check_pybcrypt(secret, hash):
"""pybcrypt"""
secret = to_native_str(secret, self.fuzz_password_encoding)
if len(secret) > 200: # vulnerable to wraparound bug
secret = secret[:200]
if hash.startswith((IDENT_2B, IDENT_2Y)):
hash = IDENT_2A + hash[4:]
try:
return bcrypt.hashpw(secret, hash) == hash
except ValueError:
raise ValueError("py-bcrypt rejected hash: %r" % (hash,))
return check_pybcrypt
def post(self):
if not self.check_unique_user(self.get_argument("parasite")):
self.render2("create_user.html")
if self.get_argument("password") == self.get_argument("password2"):
hashed_password = yield executor.submit(
bcrypt.hashpw, escape.utf8(self.get_argument("password")),
bcrypt.gensalt())
parasite_id = self.db.execute(
"INSERT INTO parasite (id, email, password, username) "
"VALUES (%s, %s, %s, %s)",
self.get_argument("parasite"), self.get_argument("email"), hashed_password,
self.get_argument("parasite"))
self.set_secure_cookie("parasite", str(parasite_id), expires_days=182)
self.redirect(self.get_argument("next", "/"))
else:
self.render2("create_user.html", error="incorrect password")
def post(self):
token = self.get_argument("token")
try:
from tornado_chat import SECRET_KEY
serializer = URLSafeTimedSerializer(SECRET_KEY)
parasite = serializer.loads(token, max_age=86400) # do i really have to do 24hrs in secs?
parasiteId = self.db.get("SELECT id, reset_token FROM parasite WHERE id = %s", parasite)
if parasiteId is not None and self.get_argument("password") == self.get_argument(
"password2") and parasiteId.reset_token == token:
hashed_password = yield executor.submit(
bcrypt.hashpw, tornado.escape.utf8(self.get_argument("password")),
bcrypt.gensalt())
self.db.execute("UPDATE parasite SET password = %s, reset_token='' WHERE id = %s", hashed_password,
parasite)
self.redirect("login?error=Password reset. Please login.")
else:
self.redirect("login?error=Password reset failed.")
except:
self.redirect("login?error=Password reset failed.")
def change_user_password(self, user, password_list):
"""
Update a user's password to the given value. Requires that the value be sent with a confirmation entry (two
identical values)
:param user: user with the password change
:param password_list: list containing password and confirmation
:return: for exiting if necessary information is not available
"""
if user != self.username or not password_list or len(password_list) != 2 or password_list[0] != password_list[
1]:
return
updating_participants = get_matching_participants(self.participants, self.current_user['id'])
hashed_password = yield executor.submit(
bcrypt.hashpw, tornado.escape.utf8(password_list[0]),
bcrypt.gensalt())
if self.current_user.password != hashed_password:
self.http_server.db.execute("UPDATE parasite SET password = %s WHERE id = %s", hashed_password,
self.current_user['id'])
self.broadcast_from_server(updating_participants, 'PASSWORD CHANGED! I hope that\'s what you wanted.')
def _calc_checksum(self, secret):
# bcrypt behavior:
# secret must be bytes
# config must be ascii bytes
# returns ascii bytes
secret, ident = self._prepare_digest_args(secret)
config = self._get_config(ident)
if isinstance(config, unicode):
config = config.encode("ascii")
hash = _bcrypt.hashpw(secret, config)
assert hash.startswith(config) and len(hash) == len(config)+31, \
"config mismatch: %r => %r" % (config, hash)
assert isinstance(hash, bytes)
return hash[-31:].decode("ascii")
#-----------------------------------------------------------------------
# bcryptor backend
#-----------------------------------------------------------------------
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!'
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')
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!'
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')