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


Python zlib.adler32方法代码示例

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


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

示例1: generate_ip_verify_hash

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def generate_ip_verify_hash(input_dict):
    """
    生成一个标示用户身份的hash
    在 human_ip_verification 功能中使用
    hash一共14位
    hash(前7位+salt) = 后7位 以此来进行验证
    :rtype str
    """
    strbuff = human_ip_verification_answers_hash_str
    for key in input_dict:
        strbuff += key + input_dict[key] + str(random.randint(0, 9000000))
    input_key_hash = hex(zlib.adler32(strbuff.encode(encoding='utf-8')))[2:]
    while len(input_key_hash) < 7:
        input_key_hash += '0'
    output_hash = hex(zlib.adler32((input_key_hash + human_ip_verification_answers_hash_str).encode(encoding='utf-8')))[2:]
    while len(output_hash) < 7:
        output_hash += '0'
    return input_key_hash + output_hash 
开发者ID:aploium,项目名称:zmirror,代码行数:20,代码来源:zmirror.py

示例2: verify_ip_hash_cookie

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def verify_ip_hash_cookie(hash_cookie_value):
    """
    根据cookie中的hash判断是否允许用户访问
    在 human_ip_verification 功能中使用
    hash一共14位
    hash(前7位+salt) = 后7位 以此来进行验证
    :type hash_cookie_value: str
    :rtype: bool
    """
    try:
        input_key_hash = hash_cookie_value[:8]
        output_hash = hash_cookie_value[8:]
        calculated_hash = hex(zlib.adler32(
            (input_key_hash + human_ip_verification_answers_hash_str).encode(encoding='utf-8')
        ))[2:]
        if output_hash == calculated_hash:
            return True
        else:
            return False
    except:
        return False 
开发者ID:aploium,项目名称:zmirror,代码行数:23,代码来源:zmirror.py

示例3: __init__

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def __init__(self, seed):
        if not seed:
            seed = "%.1f" % time.time()

        if hasattr(seed, "encode"):
            seed = seed.encode('ascii')

        # A note on hashfunctions.
        # We don't need cryptographic quality, so we won't use hashlib -
        # that'd be way to slow. The zlib module contains two hash
        # functions. Adler32 is fast, but not very uniform for short
        # strings. Crc32 is slower, but has better bit distribution.
        # So, we use crc32 whenever the hash is converted into an
        # exportable number, but we use adler32 when we're producing
        # intermediate values.
        self.seed = zlib.adler32(seed)
        self.text_seed = seed

        # Default, typically overridden
        self.size = 1024 + 786j 
开发者ID:ondergetekende,项目名称:python-panavatar,代码行数:22,代码来源:parameters.py

示例4: adler32

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def adler32(file):
    """
    An Adler-32 checksum is obtained by calculating two 16-bit checksums A and B and concatenating their bits into a 32-bit integer. A is the sum of all bytes in the stream plus one, and B is the sum of the individual values of A from each step.

    :param file: file name
    :returns: Hexified string, padded to 8 values.
    """

    # adler starting value is _not_ 0
    adler = 1

    try:
        with open(file, 'rb') as openFile:
            for line in openFile:
                adler = zlib.adler32(line, adler)
    except Exception as e:
        raise Exception('FATAL - could not get Adler32 checksum of file %s - %s' % (file, e))

    # backflip on 32bit
    if adler < 0:
        adler = adler + 2 ** 32

    return str('%08x' % adler) 
开发者ID:rucio,项目名称:rucio,代码行数:25,代码来源:utils.py

示例5: build_post

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def build_post(data):
    message = "POST /api HTTP/1.1" + "\r\n"
    message += "Host: 127.0.0.1" + "\r\n"
    message += "Content-Length: " + str(len(data)) + "\r\n"
    message += "X-Drv-Encoding: 1" + "\r\n"
    message += "\r\n"
    message = message + data
    return message

# message format
# header 7 bytes
#   magic bytes? (3 bytes)
#   length of python object (1 byte)
#   no idea (3 bytes)
# python object
# adler32 checksum (4 bytes)

# leaving sock open on purpose 
开发者ID:tenable,项目名称:poc,代码行数:20,代码来源:druva_insync_osx_lpe.py

示例6: send_rpc_request

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def send_rpc_request(sock, req_obj, unknown):
    marsh = marshal.dumps(req_obj)  # python object

    # build out the header
    header =  "\x78\x01\x01" + struct.pack('<h', len(marsh))
    header += chr(unknown) # not sure exactly what this is
    header += "\xff"

    # add the ADLER32 checksum
    checksum = struct.pack('>i', zlib.adler32(marsh))

    post_data = header + marsh + checksum
    message = build_post(post_data)
    try:
        sock.send(message)

        resp = sock.recv(1024)

        if resp is None:
            print("Did not receive a response from server.")
    except Exception as e:
        print("Error with request:")
        print(e) 
开发者ID:tenable,项目名称:poc,代码行数:25,代码来源:druva_insync_osx_lpe.py

示例7: send_rpc_request

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def send_rpc_request(sock, req_obj, unknown):
    marsh = marshal.dumps(req_obj)  # python object

    # build out the header
    header =  "\x78\x01\x01" + struct.pack('<h', len(marsh))
    header += chr(unknown) # not sure exactly what this is
    header += "\xff"

    # add the ADLER32 checksum
    checksum = struct.pack('>i', zlib.adler32(marsh))

    post_data = header + marsh + checksum
    message = build_post(post_data)
    try:
        sock.send(message)
        #print("Sent request.")

        resp = sock.recv(1024)

        if resp is None:
            print("Did not receive a response from server.")
    except Exception as e:
        print("Error with request:")
        print(e) 
开发者ID:tenable,项目名称:poc,代码行数:26,代码来源:insync_rpc_set_acl_auth_exploit.py

示例8: string_to_int_code

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def string_to_int_code(string: str) -> int:
    """
    Converts the string to an integer code representation.

    Can be used for a random seed generation from a string

    Parameters
    ----------
    string
        string to convert

    Returns
    -------
    int_code
        integer representation of the string
    """
    int_code = zlib.adler32(bytes(string, 'utf-8')) & 0xffffffff
    return int_code 
开发者ID:audi,项目名称:nucleus7,代码行数:20,代码来源:utils.py

示例9: __init__

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def __init__(self, documents=None, id_range=32000, myhash=zlib.adler32, debug=True):
        """
        By default, keep track of debug statistics and mappings. If you find yourself
        running out of memory (or are sure you don't need the debug info), set
        `debug=False`.
        """
        self.myhash = myhash # hash fnc: string->integer
        self.id_range = id_range # hash range: id = myhash(key) % id_range
        self.debug = debug

        # the following (potentially massive!) dictionaries are only formed if `debug` is True
        self.token2id = {}
        self.id2token = {} # reverse mapping int->set(words)
        self.dfs = {} # token_id -> how many documents this token_id appeared in
        self.dfs_debug = {} # token_string->how many documents this word appeared in

        self.num_docs = 0 # number of documents processed
        self.num_pos = 0 # total number of corpus positions
        self.num_nnz = 0 # total number of non-zeroes in the BOW matrix
        self.allow_update = True

        if documents is not None:
            self.add_documents(documents) 
开发者ID:largelymfs,项目名称:topical_word_embeddings,代码行数:25,代码来源:hashdictionary.py

示例10: testBuild

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def testBuild(self):
        d = HashDictionary(self.texts, myhash=zlib.adler32)
        expected =  {5232: 2,
                     5798: 3,
                     10608: 2,
                     12466: 2,
                     12736: 3,
                     15001: 2,
                     18451: 3,
                     23844: 3,
                     28591: 2,
                     29104: 2,
                     31002: 2,
                     31049: 2}

        self.assertEqual(d.dfs, expected)
        expected = {'minors': 15001, 'graph': 18451, 'system': 5798, 'trees': 23844, 'eps': 31049, 'computer': 10608, 'survey': 28591, 'user': 12736, 'human': 31002, 'time': 29104, 'interface': 12466, 'response': 5232}

        for ex in expected:
            self.assertEqual(d.token2id[ex], expected[ex]) 
开发者ID:largelymfs,项目名称:topical_word_embeddings,代码行数:22,代码来源:test_corpora_hashdictionary.py

示例11: __init__

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def __init__(self, proto: pb.Computation, name: Optional[str] = None):
    """Creates a representation of a fully constructed computation.

    Args:
      proto: An instance of pb.Computation with the computation logic.
      name: An optional string name to associate with this computation, used
        only for debugging purposes. If the name is not specified (None), it is
        autogenerated as a hexadecimal string from the hash of the proto.

    Raises:
      TypeError: if the arguments are of the wrong types.
    """
    py_typecheck.check_type(proto, pb.Computation)
    if name is not None:
      py_typecheck.check_type(name, str)
    super().__init__(type_serialization.deserialize_type(proto.type))
    self._proto = proto
    if name is not None:
      self._name = name
    else:
      self._name = '{:x}'.format(zlib.adler32(self._proto.SerializeToString())) 
开发者ID:tensorflow,项目名称:federated,代码行数:23,代码来源:building_blocks.py

示例12: __hashlib_init

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def __hashlib_init(self):
        """
        Gives the finger print to the corresponding hash library.
        """
        finger = None
        if self.hash_library.lower() == 'sha512':
            finger = hashlib.sha512()
        elif self.hash_library.lower() == 'md5':
            finger = hashlib.md5()
        elif self.hash_library.lower() == 'sha256':
            finger = hashlib.sha256()
        elif self.hash_library.lower() == 'crc32':
            finger = _crc32()
        elif self.hash_library.lower() == 'adler32':
            finger = _adler32()
        else:
            print >> sys.stderr,"ERROR: Unknown hash library!"
            self.exit_flag = False
            sys.exit(1)
        return finger

    ###
    ###  __BUILD_PATHS
    ### 
开发者ID:ndaniel,项目名称:fusioncatcher,代码行数:26,代码来源:workflow.py

示例13: recv_file

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def recv_file(self, data):
        name = os.path.join(data["path"], data["name"])
        data_remaining = data["size"]
        expected_chksum = data["chksum"]
        log.debug("receiving file: %s (%0.02fKB)", name, data_remaining/1024.0)
        chksum = 0
        with open(name, "wb") as fp:
            while data_remaining:
                data = self.recv_data()
                assert data["cmd"] == self.CHUNK, "Expecting data chunk."
                chksum = zlib.adler32(data["data"], chksum)
                fp.write(data["data"])
                data_remaining -= len(data["data"])
        if expected_chksum != chksum:
            raise RuntimeError("Checksum mismatch!") 
开发者ID:blackberry,项目名称:ALF,代码行数:17,代码来源:SockPuppet.py

示例14: send_file

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def send_file(self, src, dst=None):
        if not os.path.isfile(src):
            raise RuntimeError("%s does not exist!" % src)
        if dst is None:
            dst = os.path.basename(src)
        log.debug("sending file (%s) -> (%s)", src, dst)
        file_size = int(os.stat(src).st_size)
        chksum = 0
        with open(src, "rb") as fp:
            while fp.tell() < file_size:
                chksum = zlib.adler32(fp.read(self.CHUNK_BUF), chksum)
        data = {
                "cmd":self.FILE,
                "name":os.path.basename(dst),
                "path":os.path.dirname(dst),
                "size":file_size,
                "chksum":chksum
               }
        self.send_data(data)
        with open(src, "rb") as fp:
            data = {"cmd":self.CHUNK}
            while fp.tell() < file_size:
                data["data"] = fp.read(self.CHUNK_BUF)
                self.send_data(data)
                if len(data["data"]) < self.CHUNK_BUF:
                    break 
开发者ID:blackberry,项目名称:ALF,代码行数:28,代码来源:SockPuppet.py

示例15: perlin

# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import adler32 [as 别名]
def perlin(self, key, **kwargs):
        """Return perlin noise seede with the specified key.
        For parameters, check the PerlinNoise class."""

        if hasattr(key, "encode"):
            key = key.encode('ascii')

        value = zlib.adler32(key, self.seed)
        return PerlinNoise(value, **kwargs) 
开发者ID:ondergetekende,项目名称:python-panavatar,代码行数:11,代码来源:parameters.py


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