从 torrent 文件中提取 SHA1 哈希

新手上路,请多包涵

我已经四处寻找这个问题的答案,但我似乎只能找到适合您的软件。有人知道如何在 python 中执行此操作吗?

原文由 user271528 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

我编写了一段 python 代码,用于根据 .torrent 文件 中的内容验证 下载文件 的哈希值。假设您想检查下载是否损坏,您可能会发现这很有用。

您需要 bencode 包 才能使用它。 Bencode 是 .torrent 文件中使用的序列化格式。它可以像 JSON 一样编组列表、字典、字符串和数字。

该代码采用 info['pieces'] 字符串中包含的哈希值:

 torrent_file = open(sys.argv[1], "rb")
metainfo = bencode.bdecode(torrent_file.read())
info = metainfo['info']
pieces = StringIO.StringIO(info['pieces'])

该字符串包含一连串的 20 字节散列(每个部分一个)。然后将这些哈希值与磁盘文件片段的哈希值进行比较。

这段代码唯一复杂的部分是处理多文件 torrent,因为单个 torrent 片段 可以跨越多个文件 (在 BitTorrent 内部将多文件下载视为单个连续文件) 。我正在使用生成器函数 pieces_generator() 将其抽象化。

您可能需要阅读 BitTorrent 规范 以更详细地了解这一点。

完整代码如下:

 import sys, os, hashlib, StringIO, bencode

def pieces_generator(info):
    """Yield pieces from download file(s)."""
    piece_length = info['piece length']
    if 'files' in info: # yield pieces from a multi-file torrent
        piece = ""
        for file_info in info['files']:
            path = os.sep.join([info['name']] + file_info['path'])
            print path
            sfile = open(path.decode('UTF-8'), "rb")
            while True:
                piece += sfile.read(piece_length-len(piece))
                if len(piece) != piece_length:
                    sfile.close()
                    break
                yield piece
                piece = ""
        if piece != "":
            yield piece
    else: # yield pieces from a single file torrent
        path = info['name']
        print path
        sfile = open(path.decode('UTF-8'), "rb")
        while True:
            piece = sfile.read(piece_length)
            if not piece:
                sfile.close()
                return
            yield piece

def corruption_failure():
    """Display error message and exit"""
    print("download corrupted")
    exit(1)

def main():
    # Open torrent file
    torrent_file = open(sys.argv[1], "rb")
    metainfo = bencode.bdecode(torrent_file.read())
    info = metainfo['info']
    pieces = StringIO.StringIO(info['pieces'])
    # Iterate through pieces
    for piece in pieces_generator(info):
        # Compare piece hash with expected hash
        piece_hash = hashlib.sha1(piece).digest()
        if (piece_hash != pieces.read(20)):
            corruption_failure()
    # ensure we've read all pieces
    if pieces.read():
        corruption_failure()

if __name__ == "__main__":
    main()

原文由 Alex Jasmin 发布,翻译遵循 CC BY-SA 2.5 许可协议

下面是我如何从 torrent 文件中提取 HASH 值:

 #!/usr/bin/python

import sys, os, hashlib, StringIO
import bencode

def main():
    # Open torrent file
    torrent_file = open(sys.argv[1], "rb")
    metainfo = bencode.bdecode(torrent_file.read())
    info = metainfo['info']
    print hashlib.sha1(bencode.bencode(info)).hexdigest()

if __name__ == "__main__":
    main()

它与运行命令相同:

 transmissioncli -i test.torrent 2>/dev/null | grep "^hash:" | awk '{print $2}'

希望能帮助到你 :)

原文由 grundic 发布,翻译遵循 CC BY-SA 2.5 许可协议

推荐问题