在python 3中散列数组或对象

ske*_*rit 7 python hash md5 python-3.x

我想散列一个简单的字符串数组文档说你不能简单地将字符串输入hashlib的update()函数,所以我尝试了一个常规变量,但后来我得到了TypeError: object supporting the buffer API required错误.

这是我到目前为止所做的

def generateHash(data):
    # Prepare the project id hash
    hashId = hashlib.md5()

    hashId.update(data)

    return hashId.hexdigest()
Run Code Online (Sandbox Code Playgroud)

pep*_*epr 9

您可以使用该repr()函数来获取数组的(Unicode)字符串表示形式(或实现转换为表示形式的任何对象).然后将字符串编码为UTF-8(使用UTF-8时,每个字节的顺序都相同).您在上面尝试时可以对结果字节进行哈希处理:

#!python3
import hashlib

def hashFor(data):
    # Prepare the project id hash
    hashId = hashlib.md5()

    hashId.update(repr(data).encode('utf-8'))

    return hashId.hexdigest()


if __name__ == '__main__':
    data1 = ['abc', 'de']
    data2 = ['a', 'bcde']
    print(hashFor(data1) + ':', data1)
    print(hashFor(data2) + ':', data2)
Run Code Online (Sandbox Code Playgroud)

它在我的控制台上打印:

c:\tmp\___python\skerit\so17412304>py a.py
d26d27d8cbb7c6fe50637155c21d5af6: ['abc', 'de']
dbd5ab5df464b8bcee61fe8357f07b6e: ['a', 'bcde']
Run Code Online (Sandbox Code Playgroud)


Tho*_*zco 1

如果您想对字符串列表进行哈希处理,一个简单的解决方案可能是:

def hash_string_list(string_list):
    h = hashlib.md5()
    for s in string_list: # Note that you could use ''.join(string_list) instead
        h.update(s)       # s.encode('utf-8') if you're using Python 3
    return h.hexdigest()
Run Code Online (Sandbox Code Playgroud)

但是,请注意['abc', 'efg']['a', 'bcefg']会散列到相同的值。

如果您提供有关您的目标的更多背景信息,其他解决方案可能更合适。