【问题标题】:Python3 hashing gives different resultPython3 散列给出不同的结果
【发布时间】:2019-09-13 20:02:47
【问题描述】:

我尝试使用 Python3 代码计算加密文件 (file.gpg) 的 sha1。

我测试了两个函数。

import hashlib
import gnupg

def sha1sum(filename):
    h  = hashlib.sha1()
    b  = bytearray(128*1024)
    mv = memoryview(b)
    with open(filename, 'rb', buffering=0) as f:
        for n in iter(lambda : f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()


def sha1_checksum(filename, block_size=65536):
    sha1 = hashlib.sha1()
    with open(filename, 'rb') as f:
        for block in iter(lambda: f.read(block_size), b''):
            sha1.update(block)
    return sha1.hexdigest()

original = open('file.bin', 'rb')

gpg = gnupg.GPG()
gpg.encoding = 'utf-8'
encrypt = gpg.encrypt_file(original, 
                           recipients=None, 
                           passphrase=password,
                           symmetric='AES256', 
                           output=file)

sum = sha1sum(file)
sum = sha1_checksum(file)

脚本的第一次启动

697cee13eb4c91f41922472d8768fad076c72166
697cee13eb4c91f41922472d8768fad076c72166

脚本的第二次开始

a95593f0d8ce274492862b58108a20700ecf9d2b
a95593f0d8ce274492862b58108a20700ecf9d2b

sha1sum() 或 sha1_checksum() 错了吗?

或者文件加密给出不同的file.gpg?

【问题讨论】:

标签: python python-3.x sha1 gnupg hashlib


【解决方案1】:

这不是 Python 的问题,甚至不是 gpg 的问题。

哈希变化的原因是gpg非对称加密是非确定性的,或所谓的概率

引用wiki page Probabilistic encryption

概率加密是在加密算法中使用随机性,因此当对同一消息进行多次加密时,通常会产生不同的密文。术语“概率加密”通常用于指代公钥加密算法,但是各种对称密钥加密算法实现了类似的属性(例如,在 CBC 等链接模式中使用时的分组密码)。

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 2016-04-28
    • 2021-09-03
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多