当前位置: 首页>>代码示例>>Python>>正文


Python hashlib.algorithms_guaranteed方法代码示例

本文整理汇总了Python中hashlib.algorithms_guaranteed方法的典型用法代码示例。如果您正苦于以下问题:Python hashlib.algorithms_guaranteed方法的具体用法?Python hashlib.algorithms_guaranteed怎么用?Python hashlib.algorithms_guaranteed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在hashlib的用法示例。


在下文中一共展示了hashlib.algorithms_guaranteed方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: filehash

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def filehash(filename, block_size=65536, algorithm='sha256'):
    """
    Computes the hash value for a file by using a specified hash algorithm.

    :param filename: filename
    :type filename: str
    :param block_size: blocksize used to compute file hash
    :type block_size: int
    :param algorithm: hash algorithms like 'sha256' or 'md5' etc.
    :type algorithm: str
    :return: None
    :History: 2019-Mar-12 - Written - Henry Leung (University of Toronto)
    """
    algorithm = algorithm.lower()
    if algorithm not in hashlib.algorithms_guaranteed:
        raise ValueError(f"{algorithm} is an unsupported hashing algorithm")

    func_algorithm = getattr(hashlib, algorithm)()
    with open(filename, 'rb') as f:
        for block in iter(lambda: f.read(block_size), b''):
            func_algorithm.update(block)
    return func_algorithm.hexdigest() 
开发者ID:henrysky,项目名称:astroNN,代码行数:24,代码来源:downloader_tools.py

示例2: set_hash_function

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def set_hash_function(self, hash_function):
        """Set the hash function used.

        Args:
            hash_function (str): String representation of hash function
                Ex. 'md5'

        Returns:
            (hashlib hash function)

        """
        if "shake" in hash_function and not self.length:
            errmsg = f"{hash_function} requires length to be set"
            raise HasherError(errmsg)

        try:
            self._hash_function = getattr(hashlib, hash_function)
        except AttributeError:
            if hash_function in hashlib.algorithms_guaranteed:
                errmsg = f"{hash_function} needs Hasher implementation."
                raise HasherError(errmsg)
            errmsg = f"{hash_function} is not currently supported."
            raise HasherError(errmsg) 
开发者ID:project-koku,项目名称:koku,代码行数:25,代码来源:hash.py

示例3: get_file_hash

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def get_file_hash(image_path, algorithm="sha256"):
    """return an md5 hash of the file based on a criteria level. This
       is intended to give the file a reasonable version.
    
       Parameters
       ==========
       image_path: full path to the singularity image

    """
    try:
        hasher = getattr(hashlib, algorithm)()
    except AttributeError:
        bot.error("%s is an invalid algorithm.")
        bot.exit(" ".join(hashlib.algorithms_guaranteed))

    with open(image_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hasher.update(chunk)
    return hasher.hexdigest()


################################################################################
## FILE OPERATIONS #############################################################
################################################################################ 
开发者ID:singularityhub,项目名称:sregistry-cli,代码行数:26,代码来源:fileio.py

示例4: hash

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def hash(self, mes):
        # use hashlib.algorithms_guaranteed to list algorithms
        if self.algo == "md5":
            return hashlib.md5(mes).hexdigest()
        elif self.algo == "shortmd5": # from: http://www.peterbe.com/plog/best-hashing-function-in-python
            return hashlib.md5(mes).hexdigest().encode('base64')[:8]
        elif self.algo == "shortsha256":
            return hashlib.sha256(mes).hexdigest().encode('base64')[:8]
        elif self.algo == "minimd5":
            return hashlib.md5(mes).hexdigest().encode('base64')[:4]
        elif self.algo == "minisha256":
            return hashlib.sha256(mes).hexdigest().encode('base64')[:4]
        elif self.algo == "none":
            return ''
        else:
            raise NameError('Hashing algorithm %s is unknown!' % self.algo) 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:18,代码来源:hasher.py

示例5: sign_request

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def sign_request(sign_method, request, secret_key) -> str:
    try:
        mac_type, hash_type = map(lambda s: s.lower(), sign_method.split('-'))
        assert mac_type == 'hmac', 'Unsupported request signing method (MAC type)'
        assert hash_type in hashlib.algorithms_guaranteed, \
               'Unsupported request signing method (hash type)'

        new_api_version = request.headers.get('X-BackendAI-Version')
        legacy_api_version = request.headers.get('X-Sorna-Version')
        api_version = new_api_version or legacy_api_version
        assert api_version is not None, 'API version missing in request headers'
        body = b''
        if api_version < 'v4.20181215':
            if (request.can_read_body and
                request.content_type != 'multipart/form-data'):
                # read the whole body if neither streaming nor bodyless
                body = await request.read()
        body_hash = hashlib.new(hash_type, body).hexdigest()

        sign_bytes = ('{0}\n{1}\n{2}\nhost:{3}\ncontent-type:{4}\n'
                      'x-{name}-version:{5}\n{6}').format(
            request.method, str(request.raw_path), request['raw_date'],
            request.host, request.content_type, api_version,
            body_hash,
            name='backendai' if new_api_version is not None else 'sorna'
        ).encode()
        sign_key = hmac.new(secret_key.encode(),
                            request['date'].strftime('%Y%m%d').encode(),
                            hash_type).digest()
        sign_key = hmac.new(sign_key, request.host.encode(), hash_type).digest()
        return hmac.new(sign_key, sign_bytes, hash_type).hexdigest()
    except ValueError:
        raise AuthorizationFailed('Invalid signature')
    except AssertionError as e:
        raise InvalidAuthParameters(e.args[0]) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:37,代码来源:auth.py

示例6: test_algorithms_guaranteed

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def test_algorithms_guaranteed(self):
        self.assertEqual(hashlib.algorithms_guaranteed,
            set(_algo for _algo in self.supported_hash_names
                  if _algo.islower())) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:6,代码来源:test_hashlib.py

示例7: test_algorithms_available

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def test_algorithms_available(self):
        self.assertTrue(set(hashlib.algorithms_guaranteed).
                            issubset(hashlib.algorithms_available)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:5,代码来源:test_hashlib.py

示例8: setUp

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def setUp(self):
        """Shared variables for hasher tests."""
        super().setUp()
        self.encoding = "utf-8"
        self.hash_function = random.choice(list(hashlib.algorithms_guaranteed))
        if "shake" in self.hash_function:
            self.hasher = Hasher(
                hash_function=self.hash_function, length=random.randint(8, 64), encoding=self.encoding
            )
        else:
            self.hasher = Hasher(hash_function=self.hash_function, encoding=self.encoding)
        self.string_to_hash = "".join([random.choice(string.ascii_letters) for _ in range(16)]) 
开发者ID:project-koku,项目名称:koku,代码行数:14,代码来源:test_hash.py

示例9: process_by_url

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def process_by_url(self, url_requests):
        download_queue = []
        errors = []

        for url_request in url_requests:
            url = url_request['url']

            if self.allowed_domains:
                parsed_file_url = urlparse(url.lower())
                file_url = parsed_file_url.netloc + parsed_file_url.path
                if not any(file_url.startswith(prefix) for prefix in self.allowed_domains):
                    errors.append('File URL {} is not in list of allowed domains: {}'
                                  .format(file_url, self.allowed_domains))
                    continue

            checksums = {algo: url_request[algo] for algo in hashlib.algorithms_guaranteed
                         if algo in url_request}

            target = url_request.get('target', url.rsplit('/', 1)[-1])
            download_queue.append(DownloadRequest(url, target, checksums))

        if errors:
            raise ValueError('Errors found while processing {}: {}'
                             .format(self.URL_REQUESTS_FILENAME, ', '.join(errors)))

        return download_queue 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:28,代码来源:pre_fetch_maven_artifacts.py

示例10: test_hashlib

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def test_hashlib(self):
        import hashlib
        INPUT = b"The quick brown fox jumps over the lazy dog"
        TESTS = [
            ("sha1", "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"),
            ("sha3_512", ("01dedd5de4ef14642445ba5f5b97c15e47b9ad931326e4b0727cd94cefc44fff23f"
                          "07bf543139939b49128caf436dc1bdee54fcb24023a08d9403f9b4bf0d450")),
            ("blake2b", ("a8add4bdddfd93e4877d2746e62817b116364a1fa7bc148d95090bc7333b3673f8240"
                         "1cf7aa2e4cb1ecd90296e3f14cb5413f8ed77be73045b13914cdcd6a918")),
            ("ripemd160", "37f332f68db77bd9d7edd4969571ad671cf9dd3b"),  # OpenSSL-only
        ]
        for name, expected in TESTS:
            with self.subTest(algorithm=name):
                # With initial data
                self.assertEqual(expected, hashlib.new(name, INPUT).hexdigest())
                # Without initial data
                h = hashlib.new(name)
                h.update(INPUT)
                self.assertEqual(expected, h.hexdigest())

                if name in hashlib.algorithms_guaranteed:
                    # With initial data
                    self.assertEqual(expected, getattr(hashlib, name)(INPUT).hexdigest())
                    # Without initial data
                    h = getattr(hashlib, name)()
                    h.update(INPUT)
                    self.assertEqual(expected, h.hexdigest())
                else:
                    self.assertFalse(hasattr(hashlib, name)) 
开发者ID:chaquo,项目名称:chaquopy,代码行数:31,代码来源:test_android.py

示例11: __init__

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def __init__(self, algorithm: str, *args, **kwargs):
        if algorithm not in hashlib.algorithms_guaranteed:
            raise RuntimeError(f'Hash algorithm {algorithm} is not supported by python hashlib.')
        self.algorithm = algorithm

        super().__init__(*args, **kwargs) 
开发者ID:druids,项目名称:django-GDPR,代码行数:8,代码来源:hash_fields.py

示例12: _create_violation_hash

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def _create_violation_hash(violation_full_name, resource_data, violation_data):
    """Create a hash of violation data.

    Args:
        violation_full_name (str): The full name of the violation.
        resource_data (str): The inventory data.
        violation_data (dict): A violation.

    Returns:
        str: The resulting hex digest or '' if we can't successfully create
        a hash.
    """

    # TODO: Intelligently choose from hashlib.algorithms_guaranteed if our
    # desired one is not available.
    algorithm = 'sha512'

    try:
        violation_hash = hashlib.new(algorithm)
    except ValueError:
        LOGGER.exception('Cannot create hash for a violation with algorithm: '
                         '%s', algorithm)
        return ''

    try:
        # Group resources do not have full name.  Issue #1072
        violation_hash.update(
            json.dumps(violation_full_name).encode() +
            json.dumps(resource_data, sort_keys=True).encode() +
            json.dumps(violation_data, sort_keys=True).encode()
        )
    except TypeError:
        LOGGER.exception('Cannot create hash for a violation: %s',
                         violation_full_name)
        return ''

    return violation_hash.hexdigest() 
开发者ID:forseti-security,项目名称:forseti-security,代码行数:39,代码来源:dao.py

示例13: test_config_hash_func

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import algorithms_guaranteed [as 别名]
def test_config_hash_func(self):
        """Verify that faucet_config_hash_func is set correctly"""
        labels = self._get_info(metric=self.metrics.faucet_config_hash_func,
                                name='faucet_config_hash_func')
        hash_funcs = list(labels.values())
        self.assertEqual(len(hash_funcs), 1, "found multiple hash functions")
        hash_func = hash_funcs[0]
        # Make sure that it matches and is supported in hashlib
        self.assertEqual(hash_func, config_parser_util.CONFIG_HASH_FUNC)
        self.assertTrue(hash_func in hashlib.algorithms_guaranteed) 
开发者ID:faucetsdn,项目名称:faucet,代码行数:12,代码来源:test_valve_config.py


注:本文中的hashlib.algorithms_guaranteed方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。