python3 需要使用 pip install py3-bencode安装py3-bencode库。
pip install py3-bencode
这里使用当前目录下的 1.torrent 文件转化为磁力链接:
import bencode import hashlib import base64 #读取种子文件 torrent = open('1.torrent', 'rb').read() #计算meta数据 metadata = bencode.bdecode(torrent) hash_content = bencode.bencode(metadata['info']) digest = hashlib.sha1(hash_content).digest() b32hash = base64.b32encode(digest) print('magnet:?xt=urn:btih:%s' % b32hash.decode())
输出: