Python hashlib.sha224() Examples
The following are 30
code examples of hashlib.sha224().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
hashlib
, or try the search function
.
Example #1
Source File: test_nonce_generation.py From fastecdsa with The Unlicense | 6 votes |
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)
Example #2
Source File: probe.py From catch with MIT License | 6 votes |
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:]
Example #3
Source File: model.py From dbpy with GNU General Public License v2.0 | 6 votes |
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)
Example #4
Source File: _common.py From ALF with Apache License 2.0 | 6 votes |
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()
Example #5
Source File: user.py From hydrus with MIT License | 6 votes |
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
Example #6
Source File: context_processors.py From django-oidc-rp with MIT License | 6 votes |
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, }
Example #7
Source File: cache.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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
Example #8
Source File: source.py From PyCon-Mobile-App with GNU General Public License v3.0 | 6 votes |
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)
Example #9
Source File: kashi.py From Kashi with GNU General Public License v3.0 | 6 votes |
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])
Example #10
Source File: cache.py From Python24 with MIT License | 6 votes |
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
Example #11
Source File: cache.py From deepWordBug with Apache License 2.0 | 6 votes |
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
Example #12
Source File: cache.py From FuYiSpider with Apache License 2.0 | 6 votes |
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
Example #13
Source File: cache.py From FuYiSpider with Apache License 2.0 | 6 votes |
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
Example #14
Source File: model.py From white with GNU General Public License v2.0 | 6 votes |
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)
Example #15
Source File: snowchange.py From snowchange with Apache License 2.0 | 6 votes |
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)
Example #16
Source File: user.py From hydrus with MIT License | 6 votes |
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()
Example #17
Source File: cache.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
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
Example #18
Source File: model.py From white with GNU General Public License v2.0 | 5 votes |
def secure_password(self, password): """Encrypt password to sha224 hash""" return sha224(password).hexdigest()
Example #19
Source File: req_tracker.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def _entry_path(self, link): hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest() return os.path.join(self._root, hashed)
Example #20
Source File: wheel.py From anpr with Creative Commons Attribution 4.0 International | 5 votes |
def _cache_for_link(cache_dir, link): """ Return a directory to store cached wheels in for link. Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param cache_dir: The cache_dir being used by pip. :param link: The link of the sdist for which this will cache wheels. """ # 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:]] # Inside of the base location for cached wheels, expand our parts and join # them all together. return os.path.join(cache_dir, "wheels", *parts)
Example #21
Source File: file_cache.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def encode(x): return hashlib.sha224(x.encode()).hexdigest()
Example #22
Source File: launch.py From learning2run with MIT License | 5 votes |
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, 'ec2', '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
Example #23
Source File: test_rfc6979_ecdsa.py From fastecdsa with The Unlicense | 5 votes |
def setUpClass(cls): cls.rfc6979_text = urlopen('https://tools.ietf.org/rfc/rfc6979.txt').read().decode() cls.hash_lookup = { '1': sha1, '224': sha224, '256': sha256, '384': sha384, '512': sha512 }
Example #24
Source File: req_tracker.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def _entry_path(self, link): # type: (Link) -> str hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest() return os.path.join(self._root, hashed)
Example #25
Source File: file_cache.py From anpr with Creative Commons Attribution 4.0 International | 5 votes |
def encode(x): return hashlib.sha224(x.encode()).hexdigest()
Example #26
Source File: wheel.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _cache_for_link(cache_dir, link): """ Return a directory to store cached wheels in for link. Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param cache_dir: The cache_dir being used by pip. :param link: The link of the sdist for which this will cache wheels. """ # 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:]] # Inside of the base location for cached wheels, expand our parts and join # them all together. return os.path.join(cache_dir, "wheels", *parts)
Example #27
Source File: file_cache.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def encode(x): return hashlib.sha224(x.encode()).hexdigest()
Example #28
Source File: file_cache.py From pex with Apache License 2.0 | 5 votes |
def encode(x): return hashlib.sha224(x.encode()).hexdigest()
Example #29
Source File: req_tracker.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def _entry_path(self, link): # type: (Link) -> str hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest() return os.path.join(self._root, hashed)
Example #30
Source File: req_tracker.py From pex with Apache License 2.0 | 5 votes |
def _entry_path(self, link): # type: (Link) -> str hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest() return os.path.join(self._root, hashed)