本文整理汇总了Python中werkzeug.security.safe_str_cmp函数的典型用法代码示例。如果您正苦于以下问题:Python safe_str_cmp函数的具体用法?Python safe_str_cmp怎么用?Python safe_str_cmp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了safe_str_cmp函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_safe_str_cmp_no_builtin
def test_safe_str_cmp_no_builtin():
import werkzeug.security as sec
prev_value = sec._builtin_safe_str_cmp
sec._builtin_safe_str_cmp = None
assert safe_str_cmp('a', 'ab') is False
assert safe_str_cmp('str', 'str') is True
assert safe_str_cmp('str1', 'str2') is False
sec._builtin_safe_str_cmp = prev_value
开发者ID:brunoais,项目名称:werkzeug,代码行数:9,代码来源:test_security.py
示例2: upload_dance
def upload_dance():
if app.config['RG_VERIFY_ENDPOINT']:
user_id, user_token = request.form['user_id'], request.form['user_token']
check_token = hmac.new(app.config['RG_VERIFY_SECRET'], user_id, hashlib.sha1).hexdigest()
if not safe_str_cmp(user_token, check_token):
abort(403)
gif = request.files['moves']
gif_data = gif.read()
if gif and check_gif(gif_data):
dance_id = hashlib.sha1(gif_data).hexdigest()
dance = {
'_id': dance_id,
'ts': time.time(),
'ip': request.remote_addr,
'ua': request.user_agent.string,
'status': 'new',
}
if app.config['RG_VERIFY_ENDPOINT']:
dance['rg_id'] = user_id
g.db.save(dance)
with open(os.path.join(app.config['UPLOAD_FOLDER'], dance_id + '.gif'), 'w') as out:
out.write(gif_data)
json_data = dance_json(dance)
json_data['token'] = dance_owner_token(dance_id)
return json.jsonify(json_data)
开发者ID:chromakode,项目名称:danceparty,代码行数:26,代码来源:main.py
示例3: check_password_hash
def check_password_hash(self, password):
if PYVER < 3 and isinstance(password, unicode):
password = password.encode('u8')
elif PYVER >= 3 and isinstance(password, bytes):
password = password.decode('utf-8')
password = str(password)
return safe_str_cmp(bcrypt.hashpw(password, self.password), self.password)
开发者ID:jurex,项目名称:reactor,代码行数:7,代码来源:user.py
示例4: before_request
def before_request():
connect_db()
if request.method not in ['GET', 'HEAD', 'OPTIONS']:
if (not request.headers.get('X-CSRFT') or
not session.get('csrft') or
not safe_str_cmp(session['csrft'], request.headers['X-CSRFT'])):
abort(400)
g.is_reviewer = False
auth = request.authorization
if (auth and request.scheme == 'https' and
safe_str_cmp(auth.username, app.config['REVIEWER_USERNAME'])):
crypted = bcrypt.hashpw(auth.password, app.config['REVIEWER_PASSWORD'])
if safe_str_cmp(crypted, app.config['REVIEWER_PASSWORD']):
g.is_reviewer = True
开发者ID:chromakode,项目名称:danceparty,代码行数:16,代码来源:main.py
示例5: confirm_reset_password_token
def confirm_reset_password_token(token):
max_age_key = 'USERS_RESET_PASSWORD_TOKEN_MAX_AGE_IN_SECONDS'
max_age = current_app.config[max_age_key]
salt = current_app.config['USERS_RESET_PASSWORD_TOKEN_SALT']
serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
user, data = None, None
expired, invalid = False, False
try:
data = serializer.loads(
token,
max_age=max_age,
salt=salt)
except SignatureExpired:
d, data = serializer.loads_unsafe(token, salt=salt)
expired = True
except (BadSignature, TypeError, ValueError):
invalid = True
if data:
user = User.get(id=data[0])
if not invalid and user and user.password:
password_hash = hashlib.md5(user.password).hexdigest()
if not safe_str_cmp(password_hash, data[1]):
invalid = True
expired = expired and (user is not None)
logger.debug("reset password token confirmed?",
expired=expired, invalid=invalid, user=user, data=data)
return expired, invalid, user, data
开发者ID:oldhawaii,项目名称:oldhawaii-metadata,代码行数:35,代码来源:recoverable.py
示例6: compare_password
def compare_password(hashed_password, password):
if safe_str_cmp(bcrypt.hashpw(password.encode('utf-8'), hashed_password.encode('utf-8')), hashed_password):
print "It matches"
return True
else:
print "It does not match"
return False
开发者ID:zachgoldstein,项目名称:react-flask-boilerplate,代码行数:7,代码来源:security.py
示例7: check_password_hash
def check_password_hash(self, pw_hash, password):
'''Tests a password hash against a candidate password. The candidate
password is first hashed and then subsequently compared in constant
time to the existing hash. This will either return `True` or `False`.
Example usage of :class:`check_password_hash` would look something
like this::
pw_hash = bcrypt.generate_password_hash('secret', 10)
bcrypt.check_password_hash(pw_hash, 'secret') # returns True
:param pw_hash: The hash to be compared against.
:param password: The password to compare.
'''
# Python 3 unicode strings must be encoded as bytes before hashing.
if PY3 and isinstance(pw_hash, bytes):
pw_hash = pw_hash.decode('utf-8')
if PY3 and isinstance(password, bytes):
password = password.decode('utf-8')
if not PY3 and isinstance(pw_hash, unicode):
pw_hash = pw_hash.encode('utf-8')
if not PY3 and isinstance(password, unicode):
password = password.encode('utf-8')
return safe_str_cmp(bcrypt.hashpw(password, pw_hash), pw_hash)
开发者ID:khertan,项目名称:flask-bcrypt,代码行数:29,代码来源:flask_bcrypt.py
示例8: add_response
def add_response():
try:
token, uses = session.get('csrf', '').split(':', 1)
except:
flash('Whoa! Looks like there was a problem', 'error')
return redirect(url_for('home'))
else:
_token = request.form.get('_token', '')
_token, uses = _token.split(':', 1)
if not safe_str_cmp(token, _token) or not int(uses) <= 10:
flash('Looks like there was a problem', 'error')
return redirect(url_for('home'))
else:
session['csrf'] = '{}:{}'.format(token, int(uses) + 1)
qid = request.form.get('question', 0)
resp = request.form.get('your-answer', '')
if resp is None or '' == resp:
flash('Whoa there, enter a response.', 'error')
return redirect(url_for('question', id=qid))
resp_count = g.redis.incr('response:{}:count'.format(qid))
g.redis.set('response:{}:{}'.format(qid, resp_count), resp)
flash('Your response has been added!')
return redirect(url_for('question', id=qid))
开发者ID:Dochean,项目名称:Ask-Me-Anything,代码行数:27,代码来源:views.py
示例9: add_message
def add_message():
try:
token, uses = session.get('csrf', '').split(':', 1)
except:
flash('Whoa! Looks like there was a problem', 'error')
return redirect(url_for('home'))
else:
_token = request.form.get('_token', '')
_token, uses = _token.split(':', 1)
if not safe_str_cmp(token, _token) or not int(uses) <= 10:
flash('Looks like there was a problem', 'error')
return redirect(url_for('home'))
else:
session['csrf'] = '{}:{}'.format(token, int(uses) + 1)
msg = request.form.get('your-question')
if msg is None or '' == msg:
flash('Please ask a question', 'warning')
return redirect(url_for('home'))
count = g.redis.incr('question_counter')
if 'messages' not in session:
session['messages'] = [count]
else:
session['messages'].append(count)
g.redis.set('message:{}'.format(count), msg)
flash('Your question has been asked, just hang out here (or come back '
'later for your answers')
return redirect(url_for('listen'))
开发者ID:Dochean,项目名称:Ask-Me-Anything,代码行数:31,代码来源:views.py
示例10: remove_dance
def remove_dance(dance_id):
token = request.headers.get('X-Owner-Token')
if not token or not safe_str_cmp(token, dance_owner_token(dance_id)):
abort(403)
dance = g.db[dance_id]
dance['status'] = 'removed'
g.db.save(dance)
return '', 200
开发者ID:chromakode,项目名称:danceparty,代码行数:8,代码来源:main.py
示例11: bcrypt_check
def bcrypt_check(data, password):
import bcrypt
try:
encoded = data.encode('utf-8')
encoded2 = bcrypt.hashpw(password.encode('utf-8'), encoded)
except Exception:
raise ValueError('Invalid hash format')
return safe_str_cmp(encoded, encoded2)
开发者ID:andreymal,项目名称:mini_fiction,代码行数:8,代码来源:hashers.py
示例12: test_login
def test_login(username, password):
password = password.encode('utf-8')
pw_hash = current_app.redis.get('user:' + username + ':password')
if not pw_hash:
return False
if not safe_str_cmp(hashlib.sha1(password).hexdigest(), pw_hash):
return False
return True
开发者ID:pombredanne,项目名称:polyrents-challenge,代码行数:8,代码来源:phase2.py
示例13: is_valid_password
def is_valid_password(self, password):
"""
Check if given password is valid.
"""
return safe_str_cmp(
bcrypt.hashpw(password.encode('utf-8'), self.password_hash.encode('utf-8')),
self.password_hash
)
开发者ID:Dripitio,项目名称:drip,代码行数:8,代码来源:user.py
示例14: _token_loader
def _token_loader(token):
try:
data = _security.remember_token_serializer.loads(token)
user = _security.datastore.find_user(id=data[0])
if user and safe_str_cmp(md5(user.password), data[1]):
return user
except:
pass
return AnonymousUser()
开发者ID:Aravs7,项目名称:ubtz2,代码行数:9,代码来源:core.py
示例15: test_safe_str_cmp
def test_safe_str_cmp():
assert safe_str_cmp("a", "a") is True
assert safe_str_cmp(b"a", u"a") is True
assert safe_str_cmp("a", "b") is False
assert safe_str_cmp(b"aaa", "aa") is False
assert safe_str_cmp(b"aaa", "bbb") is False
assert safe_str_cmp(b"aaa", u"aaa") is True
assert safe_str_cmp(u"aaa", u"aaa") is True
开发者ID:pallets,项目名称:werkzeug,代码行数:8,代码来源:test_security.py
示例16: scrypt_check
def scrypt_check(data, password):
try:
salt, Nexp, r, p, keylen, h = data.split('$')
Nexp = int(Nexp, 10)
r = int(r, 10)
p = int(p, 10)
keylen = int(keylen, 10)
except Exception:
raise ValueError('Invalid hash format')
return safe_str_cmp(h, _scrypt_password_hash(password, salt, Nexp, r, p, keylen))
开发者ID:andreymal,项目名称:mini_fiction,代码行数:10,代码来源:hashers.py
示例17: authenticate
def authenticate(username, password):
"""
Function that gets called when a user calls the /auth endpoint with their username and password
:param username: User's username in string format.
:param password: User's un-encrypted password in string format.
:return: A user if authentication was successful, None otherwise.
"""
user = UserModel.find_by_username(username)
if user and safe_str_cmp(user.password, password):
return user
开发者ID:b9007,项目名称:Python,代码行数:11,代码来源:security.py
示例18: unserialize
def unserialize(cls, string, secret_key):
"""Load the secure cookie from a serialized string.
:param string: the cookie value to unserialize.
:param secret_key: the secret key used to serialize the cookie.
:return: a new :class:`SecureCookie`.
"""
# explicitly convert it into a bytestring because python 2.6
# no longer performs an implicit string conversion on hmac
secret_key = str(secret_key)
if isinstance(string, unicode):
string = string.encode('utf-8', 'replace')
try:
base64_hash, data = string.split('?', 1)
except (ValueError, IndexError):
items = ()
else:
items = {}
mac = hmac(secret_key, None, cls.hash_method)
for item in data.split('&'):
mac.update('|' + item)
if not '=' in item:
items = None
break
key, value = item.split('=', 1)
# try to make the key a string
key = url_unquote_plus(key)
try:
key = str(key)
except UnicodeError:
pass
items[key] = value
# no parsing error and the mac looks okay, we can now
# sercurely unpickle our cookie.
try:
client_hash = base64_hash.decode('base64')
except Exception:
items = client_hash = None
if items is not None and safe_str_cmp(client_hash, mac.digest()):
try:
for key, value in items.iteritems():
items[key] = cls.unquote(value)
except UnquoteError:
items = ()
else:
if '_expires' in items:
if time() > items['_expires']:
items = ()
else:
del items['_expires']
else:
items = ()
return cls(items, secret_key, False)
开发者ID:aspectit,项目名称:werkzeug,代码行数:54,代码来源:securecookie.py
示例19: pbkdf2_check
def pbkdf2_check(data, password):
try:
algorithm, iterations, salt, _ = data.split('$', 3)
iterations = int(iterations)
except Exception:
raise ValueError('Invalid hash format')
if algorithm != 'pbkdf2_sha256':
raise ValueError('Unknown pbkdf2 algorithm variant')
data2 = pbkdf2_encode(password, salt, iterations)
return safe_str_cmp(data, data2)
开发者ID:andreymal,项目名称:mini_fiction,代码行数:11,代码来源:hashers.py
示例20: authenticate
def authenticate(username, password):
"""
Checks if the user which is supplied in the /POST request exists
:param username: username field in the JSON
:param password: password field in the JSON
:return: user_id
"""
username_table = {u.username: u for u in users}
user = username_table.get(username, None)
if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
return user
开发者ID:Zwennes,项目名称:vertica_zappa_api,代码行数:11,代码来源:application.py
注:本文中的werkzeug.security.safe_str_cmp函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论