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


Python hashlib.blake2b方法代码示例

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


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

示例1: _get_hashes

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def _get_hashes(path: Path) -> Dict[str, str]:
        sha256_manager = hashlib.sha256()
        md5_manager = hashlib.md5()
        if hasattr(hashlib, 'blake2b'):
            blake2_manager = hashlib.blake2b(digest_size=32)
        else:
            blake2_manager = None
        with path.open('rb') as stream:
            while True:
                data = stream.read(65536)
                if not data:
                    break
                sha256_manager.update(data)
                md5_manager.update(data)
                if blake2_manager:
                    blake2_manager.update(data)
        return dict(
            md5_digest=md5_manager.hexdigest(),
            sha256_digest=sha256_manager.hexdigest(),
            blake2_256_digest=blake2_manager.hexdigest(),
        ) 
开发者ID:dephell,项目名称:dephell,代码行数:23,代码来源:_uploader.py

示例2: test_hash_same_as_nonchunked

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def test_hash_same_as_nonchunked(self, event_loop, mock_dataset_with_manifest):
        ds, manifest, working_dir = mock_dataset_with_manifest
        sh = SmartHash(ds.root_dir, manifest.cache_mgr.cache_root, manifest.dataset_revision)
        cache_dir = manifest.cache_mgr.cache_root
        revision = manifest.dataset_revision

        filename = "test1.txt"
        helper_append_file(cache_dir, revision, filename, "asdfdsfgkdfshuhwedfgft345wfd" * 100000)
        assert sh.fast_hash_data == {}
        assert sh.is_cached(filename) is False
        assert os.path.exists(os.path.join(cache_dir, revision, ".smarthash")) is False

        hash_result = await sh.hash([filename])
        hash_result = hash_result[0]
        h = blake2b()
        with open(sh.get_abs_path(filename), 'rb') as fh:
            h.update(fh.read())

        assert hash_result == h.hexdigest() 
开发者ID:gigantum,项目名称:gigantum-client,代码行数:21,代码来源:test_hash.py

示例3: __init__

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def __init__(self, code: str, key: bytes, ns_manager: BuiltInManager):
        self.symbol_table: symtable = symtable(code, '<string>', 'exec')
        self.code: str = code
        self.input_vars: List[SymbolWrapper] = CodeObject._find_input_variables(self.symbol_table, ns_manager
                                                                                )
        self.output_vars: FrozenSet[SymbolWrapper] = CodeObject._find_output_variables(self.symbol_table
                                                                                       )

        h = blake2b(digest_size=10, key=key)
        if len(self.output_vars) > 0:
            display_id_prefix = "+".join(map(str, self.output_vars))
            h.update(display_id_prefix.encode('utf-8'))
            self.display_id = f"{display_id_prefix}-{h.hexdigest()}"
        else:
            h.update(self.code.encode('utf-8'))
            self.display_id = f"{h.hexdigest()}" 
开发者ID:jupytercalpoly,项目名称:reactivepy,代码行数:18,代码来源:code_object.py

示例4: ss58_encode

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def ss58_encode(address, address_type=42):
    checksum_prefix = b'SS58PRE'

    if type(address) is bytes or type(address) is bytearray:
        address_bytes = address
    else:
        address_bytes = bytes.fromhex(address)

    if len(address_bytes) == 32:
        # Checksum size is 2 bytes for public key
        checksum_length = 2
    elif len(address_bytes) in [1, 2, 4, 8]:
        # Checksum size is 1 byte for account index
        checksum_length = 1
    else:
        raise ValueError("Invalid length for address")

    address_format = bytes([address_type]) + address_bytes
    checksum = blake2b(checksum_prefix + address_format).digest()

    return base58.b58encode(address_format + checksum[:checksum_length]).decode() 
开发者ID:polkascan,项目名称:py-scale-codec,代码行数:23,代码来源:ss58.py

示例5: create_from_account_list

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def create_from_account_list(cls, accounts, threshold):
        from scalecodec.utils.ss58 import ss58_decode

        account_ids = []
        for account in accounts:
            if account[0:2] != '0x':
                account = '0x{}'.format(ss58_decode(account))
            account_ids.append(account)

        account_list_cls = cls.get_decoder_class('Vec<AccountId>')
        account_list_data = account_list_cls.encode(sorted(account_ids))
        threshold_data = cls.get_decoder_class("u16").encode(threshold)

        multi_account_id = "0x{}".format(blake2b(
            b"modlpy/utilisuba" + bytes(account_list_data.data) + bytes(threshold_data.data), digest_size=32
        ).digest().hex())

        multi_account_obj = cls()
        multi_account_obj.encode(multi_account_id)

        return multi_account_obj 
开发者ID:polkascan,项目名称:py-scale-codec,代码行数:23,代码来源:types.py

示例6: make_key

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def make_key(self, key: Union[str, handlers.HandlerId], max_length: int = 63) -> str:

        # K8s has a limitation on the allowed charsets in annotation/label keys.
        # https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/#syntax-and-character-set
        safe_key = key.replace('/', '.')

        # K8s has a limitation of 63 chars per annotation/label key.
        # Force it to 63 chars by replacing the tail with a consistent hash (with full alphabet).
        # Force it to end with alnums instead of altchars or trailing chars (K8s requirement).
        prefix = f'{self.prefix}/' if self.prefix else ''
        if len(safe_key) <= max_length - len(prefix):
            suffix = ''
        else:
            digest = hashlib.blake2b(safe_key.encode('utf-8'), digest_size=4).digest()
            alnums = base64.b64encode(digest, altchars=b'-.').decode('ascii')
            suffix = f'-{alnums}'.rstrip('=-.')

        full_key = f'{prefix}{safe_key[:max_length - len(prefix) - len(suffix)]}{suffix}'
        return full_key 
开发者ID:zalando-incubator,项目名称:kopf,代码行数:21,代码来源:progress.py

示例7: __init__

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def __init__(self, pw=None):
        """
        Args:
            pw (byte-like): A password that deterministically generates the key.
        """
        super().__init__()
        if not pw:
            self.key = None
            self.keyParams = None
            return
        # If a password was provided, create a new set of key parameters and an
        # authentication code.
        salt = rando.newKey()
        _, hashName, iterations = defaultKDFParams()
        b = ByteArray(
            hashlib.pbkdf2_hmac(hashName, bytes(pw), salt.bytes(), iterations)
        )
        self.key = b[:32]
        self.keyParams = KDFParams(salt)
        authKey = b[32:].bytes()
        authMsg = self.keyParams.baseParams().bytes()
        self.keyParams.auth = ByteArray(
            hashlib.blake2b(authMsg, digest_size=32, key=authKey).digest()
        ) 
开发者ID:decred,项目名称:tinydecred,代码行数:26,代码来源:crypto.py

示例8: blake2bchecksum

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def blake2bchecksum(file_path):
    """
    Calculates hash of the file

    Parameters
    ----------
    file_path : str
        path to the file
    """
    with open(file_path, 'rb') as fh:
        m = hashlib.blake2b()
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        return m.hexdigest() 
开发者ID:machine-intelligence-laboratory,项目名称:TopicNet,代码行数:19,代码来源:routine.py

示例9: sign

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def sign(self, key):
        '''Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        '''
        h = blake2b(digest_size=32)
        h.update(rlp.encode(self, ThorTransaction.exclude(["Signature"])))
        rawhash = h.digest()

        if key in (0, "", b"\x00" * 32, "0" * 64):
            raise Exception("Zero privkey cannot sign")

        if len(key) == 64:
            key = to_bytes(hexstr=key)  # we need a binary key
        pk = keys.PrivateKey(key)

        self.Signature = pk.sign_msg_hash(rawhash).to_bytes()


#
# estimate eth gas
# 
开发者ID:vechain,项目名称:web3-gear,代码行数:24,代码来源:compat.py

示例10: blake

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def blake(x):
    return blake2b(x).digest()[:32] 
开发者ID:ethereum,项目名称:beacon_chain,代码行数:4,代码来源:blake.py

示例11: hash

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def hash(x):
    return blake2b(x).digest()[:32] 
开发者ID:ethereum,项目名称:beacon_chain,代码行数:4,代码来源:hash_ssz.py

示例12: hash

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def hash(self) -> str:
        """ Returns the Blake2b hash of the view """
        b2b = hashlib.blake2b()
        with open(self._path, "rb") as f:
            for chunk in iter(lambda: f.read(8192), b""):
                b2b.update(chunk)
        return b2b.hexdigest() 
开发者ID:MolSSI,项目名称:QCPortal,代码行数:9,代码来源:dataset_view.py

示例13: get_name

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def get_name( s ):
    full_name = s.get_full_name()
    if len(full_name) < 64:
      return full_name
    param_hash = blake2b(digest_size = 8)
    param_hash.update(s.get_field_str().encode('ascii'))
    return f'{s.cls.__name__}__{param_hash.hexdigest()}'

  # def get_file_info( s ):
    # return s.file_info 
开发者ID:pymtl,项目名称:pymtl3,代码行数:12,代码来源:RTLIRDataType.py

示例14: get_component_unique_name

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def get_component_unique_name( c_rtype ):
  full_name = get_component_full_name( c_rtype )
  special_chars = [' ', '<', '>', '.']

  if len( full_name ) < 64 and not any([c in full_name for c in special_chars]):
    return full_name

  comp_name = c_rtype.get_name()
  param_hash = blake2b(digest_size = 8)
  param_hash.update(full_name[len(comp_name):].encode('ascii'))
  param_name = param_hash.hexdigest()
  return comp_name + "__" + param_name 
开发者ID:pymtl,项目名称:pymtl3,代码行数:14,代码来源:utility.py

示例15: get_file_hash

# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import blake2b [as 别名]
def get_file_hash( file_path ):
  with open(file_path) as fd:
    hash_inst = blake2b()
    string = ''.join( fd.readlines() ).encode( 'ascii' )
    hash_inst.update(string)
    return hash_inst.hexdigest() 
开发者ID:pymtl,项目名称:pymtl3,代码行数:8,代码来源:utility.py


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