本文整理匯總了Python中hashlib.sha224方法的典型用法代碼示例。如果您正苦於以下問題:Python hashlib.sha224方法的具體用法?Python hashlib.sha224怎麽用?Python hashlib.sha224使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類hashlib
的用法示例。
在下文中一共展示了hashlib.sha224方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: authenticate_user
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def authenticate_user(id_: int, paraphrase: str, session: Session) -> bool:
"""Authenticate a user based on the ID and his paraphrase.
Raises:
UserNotFound: If a user with `id_` is not a valid/defined User
"""
user = None
try:
user = session.query(User).filter(User.id == id_).one()
except NoResultFound:
raise UserNotFound(id_=id_)
hashvalue = user.paraphrase
generated_hash = sha224(paraphrase.encode('utf-8')).hexdigest()
return generated_hash == hashvalue
示例2: _calc_hash
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def _calc_hash(self, max_depth, use_offset):
hasher = hashlib.sha224()
for s in self.backtrace[:max_depth]:
sym = s.get_str(include_offset=False)
if not sym:
sym = "Unknown"
else:
sym = sym.lower()
hasher.update(sym)
if use_offset:
# to be consistant make sure we are dealing with an int not a str that could be
# base 10 or 16 or 0X or 0x...
offset = s.off if s.off is not None else 0
assert isinstance(offset, int) or (hasattr(__builtins__, "long") and isinstance(offset, long)), \
"Offset is %s should be int. Value: %s" % (type(offset), offset)
hasher.update(str(offset))
# sha224 is 224bits or 28 bytes or 56 hex chars
return hasher.hexdigest().upper()
示例3: oidc
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def oidc(request):
""" Inserts OIDC-related values into the context. """
global _anonymous_session_state
if _anonymous_session_state is None and oidc_rp_settings.UNAUTHENTICATED_SESSION_MANAGEMENT_KEY:
salt = md5(uuid.uuid4().hex.encode()).hexdigest()
browser_state = sha224(
oidc_rp_settings.UNAUTHENTICATED_SESSION_MANAGEMENT_KEY.encode('utf-8')).hexdigest()
session_state = '{client_id} {origin} {browser_state} {salt}'.format(
client_id=oidc_rp_settings.CLIENT_ID,
origin='{}://{}'.format(request.scheme, RequestSite(request).domain),
browser_state=browser_state, salt=salt)
_anonymous_session_state = sha256(session_state.encode('utf-8')).hexdigest() + '.' + salt
return {
'oidc_op_url': oidc_rp_settings.PROVIDER_URL,
'oidc_op_endpoint': oidc_rp_settings.PROVIDER_ENDPOINT,
'oidc_client_id': oidc_rp_settings.CLIENT_ID,
'oidc_anonymous_session_state': _anonymous_session_state,
}
示例4: __init__
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def __init__(self, username, email, real_name, password, bio, status, role='user', uid=None):
"""If the user load from database, if will intialize the uid and secure password.
Otherwise will hash encrypt the real password
arg role enum: the string in ('user', 'editor', 'administrator')
arg status enum: the string in ('actived', 'inactive')
arg password fix legnth string: the use sha224 password hash
"""
self.username = username
self.email = email
self.real_name = real_name
self.bio = bio
self.status = status
self.role = role
if uid:
self.uid = uid
self.password = password
else:
self.password = self.secure_password(password)
示例5: _get_cache_path_parts
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def _get_cache_path_parts(self, link):
"""Get parts of part that must be os.path.joined with cache_dir
"""
# We want to generate an url to use as our cache key, we don't want to
# just re-use the URL because it might have other items in the fragment
# and we don't care about those.
key_parts = [link.url_without_fragment]
if link.hash_name is not None and link.hash is not None:
key_parts.append("=".join([link.hash_name, link.hash]))
key_url = "#".join(key_parts)
# Encode our key url with sha224, we'll use this because it has similar
# security properties to sha256, but with a shorter total output (and
# thus less secure). However the differences don't make a lot of
# difference for our use case here.
hashed = hashlib.sha224(key_url.encode()).hexdigest()
# We want to nest the directories some to prevent having a ton of top
# level directories where we might run out of sub directories on some
# FS.
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts
示例6: apply_change_script
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def apply_change_script(script, change_history_table, verbose):
# First read the contents of the script
with open(script['script_full_path'],'r') as content_file:
content = content_file.read().strip()
content = content[:-1] if content.endswith(';') else content
# Define a few other change related variables
checksum = hashlib.sha224(content.encode('utf-8')).hexdigest()
execution_time = 0
status = 'Success'
# Execute the contents of the script
if len(content) > 0:
start = time.time()
execute_snowflake_query('', content, verbose)
end = time.time()
execution_time = round(end - start)
# Finally record this change in the change history table
query = "INSERT INTO {0}.{1} (VERSION, DESCRIPTION, SCRIPT, SCRIPT_TYPE, CHECKSUM, EXECUTION_TIME, STATUS, INSTALLED_BY, INSTALLED_ON) values ('{2}','{3}','{4}','{5}','{6}',{7},'{8}','{9}',CURRENT_TIMESTAMP);".format(change_history_table['schema_name'], change_history_table['table_name'], script['script_version'], script['script_description'], script['script_name'], script['script_type'], checksum, execution_time, status, os.environ["SNOWFLAKE_USER"])
execute_snowflake_query(change_history_table['database_name'], query, verbose)
示例7: _get_cache_path_parts
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def _get_cache_path_parts(self, link):
# type: (Link) -> List[str]
"""Get parts of part that must be os.path.joined with cache_dir
"""
# We want to generate an url to use as our cache key, we don't want to
# just re-use the URL because it might have other items in the fragment
# and we don't care about those.
key_parts = [link.url_without_fragment]
if link.hash_name is not None and link.hash is not None:
key_parts.append("=".join([link.hash_name, link.hash]))
key_url = "#".join(key_parts)
# Encode our key url with sha224, we'll use this because it has similar
# security properties to sha256, but with a shorter total output (and
# thus less secure). However the differences don't make a lot of
# difference for our use case here.
hashed = hashlib.sha224(key_url.encode()).hexdigest()
# We want to nest the directories some to prevent having a ton of top
# level directories where we might run out of sub directories on some
# FS.
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts
示例8: __init__
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def __init__(self, username, email, real_name, password, bio, status, role='user', uid=None):
"""If the user load from database, if will intialize the uid and secure password.
Otherwise will hash encrypt the real password
arg role enum: the string in ('root', 'user', 'editor', 'administrator')
arg status enum: the string in ('active', 'inactive')
arg password fix legnth string: the use sha224 password hash
"""
self.username = username
self.email = email
self.real_name = real_name
self.bio = bio
self.status = status
self.role = role
if uid is not None:
self.uid = uid
self._password = password
else:
self._password = self.secure_password(password)
示例9: printWisdom
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def printWisdom(player_song):
wisdom = [
'\"Music expresses that which cannot be said and on which it is impossible to be silent.\" - Victor Hugo ',
'\"If music be the food of love, play on.\" - William Shakespeare ',
'\"Where words fail, music speaks.\" - Hans Christian Anderson ',
'\"One good thing about music, when it hits you, you feel no pain.\" - Bob Marley ',
'\"And those who were seen dancing were thought to be insane by those who could not hear the music.\" - Nietzsche ',
'\"There is geometry in the humming of the strings, there is music in the spacing of the spheres.\" - Pythagoras ',
'\"You are the music while the music lasts.\" - T. S. Eliot ',
'\"After silence, that which comes nearest to expressing the inexpressible is music.\" - Aldous Huxley '
]
# Hash songname for constant quote when script refires
songhash = hashlib.sha224(player_song.encode('utf-8')).hexdigest()
songhash_int = int(songhash, base=16)
# Reduce hash to within array length
print(wisdom[(songhash_int % (len(wisdom) + 1)) - 1])
示例10: __init__
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def __init__(self,
url="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
cache_key=None, min_zoom=0, max_zoom=19, tile_size=256,
image_ext="png",
attribution="© OpenStreetMap contributors",
subdomains="abc", **kwargs):
super(MapSource, self).__init__()
if cache_key is None:
# possible cache hit, but very unlikely
cache_key = hashlib.sha224(url.encode("utf8")).hexdigest()[:10]
self.url = url
self.cache_key = cache_key
self.min_zoom = min_zoom
self.max_zoom = max_zoom
self.tile_size = tile_size
self.image_ext = image_ext
self.attribution = attribution
self.subdomains = subdomains
self.cache_fmt = "{cache_key}_{zoom}_{tile_x}_{tile_y}.{image_ext}"
self.dp_tile_size = min(dp(self.tile_size), self.tile_size * 2)
self.default_lat = self.default_lon = self.default_zoom = None
self.bounds = None
self.cache_dir = kwargs.get('cache_dir', CACHE_DIR)
示例11: test_rfc_6979
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def test_rfc_6979(self):
msg = 'sample'
x = 0x09A4D6792295A7F730FC3F2B49CBC0F62E862272F
q = 0x4000000000000000000020108A2E0CC0D99F8A5EF
expected = 0x09744429FA741D12DE2BE8316E35E84DB9E5DF1CD
nonce = RFC6979(msg, x, q, sha1).gen_nonce()
self.assertTrue(nonce == expected)
expected = 0x323E7B28BFD64E6082F5B12110AA87BC0D6A6E159
nonce = RFC6979(msg, x, q, sha224).gen_nonce()
self.assertTrue(nonce == expected)
expected = 0x23AF4074C90A02B3FE61D286D5C87F425E6BDD81B
nonce = RFC6979(msg, x, q, sha256).gen_nonce()
self.assertTrue(nonce == expected)
expected = 0x2132ABE0ED518487D3E4FA7FD24F8BED1F29CCFCE
nonce = RFC6979(msg, x, q, sha384).gen_nonce()
self.assertTrue(nonce == expected)
expected = 0x00BBCC2F39939388FDFE841892537EC7B1FF33AA3
nonce = RFC6979(msg, x, q, sha512).gen_nonce()
self.assertTrue(nonce == expected)
示例12: identifier
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def identifier(self, length=10):
"""Return an identifier for this probe, based on its sequence.
The identifier is probably unique among all the probes being
considered.
The identifier is computed from a hash of this probe's sequence
(self.seq_str); it is the final 'length' hex digits of the
hash. Python's hash(..) function could be used, but the size of
the hashes it produces depends on the size of the input (longer
input yield larger hashes); using the SHA-224 hash function
should produce more uniform hash values.
For example, when length=10, this is equivalent to taking the final
40 bits of the SHA-224 digest since each hex digit is 4 bits.
Thus, it is the SHA-224 digest modulo 2^40. There are 2^40 (roughly
one trillion) possible identifiers for a probe.
Returns:
a (probably) unique identifier for this probe, as a string
"""
return hashlib.sha224(self.seq_str.encode()).hexdigest()[-length:]
示例13: add_user
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def add_user(id_: int, paraphrase: str, session: Session) -> None:
"""Add new users to the database.
Raises:
UserExits: If a user with `id_` already exists.
"""
if session.query(exists().where(User.id == id_)).scalar():
raise UserExists(id_=id_)
else:
new_user = User(id=id_, paraphrase=sha224(
paraphrase.encode('utf-8')).hexdigest())
session.add(new_user)
session.commit()
示例14: generate_basic_digest
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def generate_basic_digest(id_: int, paraphrase: str) -> str:
"""Create the digest to be added to the HTTP Authorization header."""
paraphrase_digest = sha224(paraphrase.encode('utf-8')).hexdigest()
credentials = '{}:{}'.format(id_, paraphrase_digest)
digest = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
return digest
示例15: upload_archive
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha224 [as 別名]
def upload_archive(exp_name, archive_excludes, s3_bucket):
import hashlib, os.path as osp, subprocess, tempfile, uuid, sys
# Archive this package
thisfile_dir = osp.dirname(osp.abspath(__file__))
pkg_parent_dir = osp.abspath(osp.join(thisfile_dir, '..', '..'))
pkg_subdir = osp.basename(osp.abspath(osp.join(thisfile_dir, '..')))
assert osp.abspath(__file__) == osp.join(pkg_parent_dir, pkg_subdir, 'scripts', 'launch.py'), 'You moved me!'
# Run tar
tmpdir = tempfile.TemporaryDirectory()
local_archive_path = osp.join(tmpdir.name, '{}.tar.gz'.format(uuid.uuid4()))
tar_cmd = ["tar", "-zcvf", local_archive_path, "-C", pkg_parent_dir]
for pattern in archive_excludes:
tar_cmd += ["--exclude", pattern]
tar_cmd += ["-h", pkg_subdir]
highlight(" ".join(tar_cmd))
if sys.platform == 'darwin':
# Prevent Mac tar from adding ._* files
env = os.environ.copy()
env['COPYFILE_DISABLE'] = '1'
subprocess.check_call(tar_cmd, env=env)
else:
subprocess.check_call(tar_cmd)
# Construct remote path to place the archive on S3
with open(local_archive_path, 'rb') as f:
archive_hash = hashlib.sha224(f.read()).hexdigest()
remote_archive_path = '{}/{}_{}.tar.gz'.format(s3_bucket, exp_name, archive_hash)
# Upload
upload_cmd = ["aws", "s3", "cp", local_archive_path, remote_archive_path]
highlight(" ".join(upload_cmd))
subprocess.check_call(upload_cmd)
presign_cmd = ["aws", "s3", "presign", remote_archive_path, "--expires-in", str(60 * 60 * 24 * 30)]
highlight(" ".join(presign_cmd))
remote_url = subprocess.check_output(presign_cmd).decode("utf-8").strip()
return remote_url