从种子文件中提取SHA1哈希
家电修理 2023-07-16 19:17www.caominkang.com电器维修
我写了一段python代码,根据 .torrent文件 中的内容验证 下载文件 的哈希值。假设您要检查下载是否损坏,则可能会发现此功能有用。 __
您需要benpre包才能使用它。Benpre是.torrent文件中使用的序列化格式。它可以封送列表,字典,字符串和数字,就像JSON。
该代码采用
info['pieces']字符串中包含的哈希值
torrent_file = open(sys.argv[1], "rb")metainfo = benpre.bdepre(torrent_file.read())info = metainfo['info']pieces = StringIO.StringIO(info['pieces'])
该字符串包含连续的20个字节的哈希值(每段一个)。然后,将这些哈希与磁盘文件碎片的哈希进行比较。
此代码的唯一复杂部分被处理多文件种子因为单个洪流 片 可以跨越多于一个文件 (内部BitTorrent的治疗多文件下载作为单个连续文件)
。我正在使用生成器函数
pieces_generator()将其抽象化。
您可能需要阅读BitTorrent规范以更详细地了解这一点。
完整代码如下
import sys, os, hashlib, StringIO, benpredef pieces_generator(info): """Yield pieces from donload 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.depre('UTF-8'), "rb") hile 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.depre('UTF-8'), "rb") hile True: piece = sfile.read(piece_length) if not piece: sfile.close() return yield piecedef corruption_failure(): """Display error message and exit""" print("donload corrupted") exit(1)def main(): # Open torrent file torrent_file = open(sys.argv[1], "rb") metainfo = benpre.bdepre(torrent_file.read()) info = metainfo['info'] pieces = StringIO.StringIO(info['pieces']) # Iterate through pieces for piece in pieces_generator(info): # Compare piece hash ith expected hash piece_hash = hashlib.sha1(piece).digest() if (piece_hash != pieces.read(20)): corruption_failure() # ensure e've read all pieces if pieces.read(): corruption_failure()if __name__ == "__main__": main()空调维修
- 我的世界电脑版运行身份怎么弄出来(我的世界
- 空调抽湿是什么意思,设置抽湿的温度有什么意
- 方太燃气灶有一个打不着火 怎么修复与排查方法
- 夏季免费清洗汽车空调的宣传口号
- 清洗完空调后出现漏水现象
- iphone6能玩什么游戏(iphone6游戏)
- 如何设置电脑密码锁屏(如何设置电脑密码锁屏
- win10删除开机密码提示不符合密码策略要求
- 电脑w7显示不是正版(w7不是正版怎么解决)
- 万家乐z8热水器显示e7解决 怎么修复与排查方法
- 1匹空调多少瓦数(1匹空调多少瓦)
- 安卓手机连接电脑用什么软件好(关于安卓手机
- 电脑网页看视频卡是什么原因(爱拍看视频卡)
- 华帝燃气灶点火器一直响然后熄火怎么办:问题
- 电脑壁纸怎么换(关于电脑壁纸怎么换的介绍)
- 冬天空调的出风口应该朝什么方向(冬天空调风