Python 3.x 在python3中使用SHA1进行哈希运算不会产生相同的结果

Python 3.x 在python3中使用SHA1进行哈希运算不会产生相同的结果,python-3.x,hash,sha1,Python 3.x,Hash,Sha1,我正在尝试编写一些代码来防止修改列表的更新。为此,我正在计算值的SHA1散列,但当我重新启动ipython解释器时,该散列的hexdigest()会产生不同的结果。为什么会这样 In [1]: import hashlib In [2]: hashid = hashlib.sha1() In [3]: hashid.update(repr(frozenset(sorted(["a","b","c"]))).encode("utf-8")) In [4]: hashid.hexdigest(

我正在尝试编写一些代码来防止修改列表的更新。为此,我正在计算值的SHA1散列,但当我重新启动ipython解释器时,该散列的hexdigest()会产生不同的结果。为什么会这样

In [1]: import hashlib

In [2]: hashid = hashlib.sha1()

In [3]: hashid.update(repr(frozenset(sorted(["a","b","c"]))).encode("utf-8"))

In [4]: hashid.hexdigest()
Out[4]: '53ca01b21fd7cb1996634bb45ad74851f73c45d3'
在同一ipython3控制台中重新初始化哈希ID并再次执行哈希计算时,它会起作用:

In [5]: hashid = hashlib.sha1()

In [6]: hashid.update(repr(frozenset(sorted(["a","b","c"]))).encode("utf-8"))

In [7]: hashid.hexdigest()
Out[7]: '53ca01b21fd7cb1996634bb45ad74851f73c45d3'
但停止并重新启动控制台会产生不同的结果:

In [7]: exit
rvl@laptop ~/ $ ipython3 
In [1]: import hashlib

In [2]: hashid = hashlib.sha1()

In [3]: hashid.update(repr(frozenset(sorted(["a","b","c"]))).encode("utf-8"))

In [4]: hashid.hexdigest()
Out[4]: '6e5813fcb173e35e81d6138eab4d21482885e7eb'

为什么会这样?当具有相同的排序列表时,如何生成相同的SHA1哈希/hexdigest结果?

您不能依赖
集合
/
冻结集
对象的
repr
的顺序,因为值没有保证的顺序(事实上,作为一种抗拒绝服务功能,在同一版本Python的不同运行中,字符串的哈希代码会有所不同,从而导致
set
顺序发生变化)

交换
frozenset
sorted
调用,以获得一致的再现表示。sorted
list
s保证了顺序,而
frozenset
将保证唯一性:

hashid.update(repr(sorted(frozenset(["a","b","c"]))).encode("utf-8"))

啊,tnx,这是有道理的…可能花了几个小时来寻找这个。这澄清了很多。请不要在回答上添加评论说“谢谢”。如果答案对你有帮助。顺便说一句,你被问了29个问题,但只接受了第一个。为什么?