How do I calculate the hash of a torrent file with PHP?
I already used the class BEncoded
and it worked, but wanted to know how it works.
How do I calculate the hash of a torrent file with PHP?
I already used the class BEncoded
and it worked, but wanted to know how it works.
A torrent file has a data structure with two highest level keys: announce
- identifying the tracker (s) to be used for download - and info
- containing the names of the files and the relevant hashes (of the pieces, I believe, but I'm not sure). To create magnet links, use infohash
, which is just a hash of the info
encoded data. Font .
In order to calculate this infohash
it is necessary to open the torrent file, interpret its structure and calculate the hash of the relevant part (from what I understand above, I do not need to decode a but it is still necessary to select it inside the file).
The detail is that since infohash
is a hash of the encoded structure, and BencodeModel
decodes everything, it becomes necessary to re-encode the relevant part before applying the hash:
Decode and get the relevant part ( info
):
$bencode = new BencodeModel();
$data = $bencode->decode_file($form->fields['filename']->saved_file);
$hash = $torrentmanager->create_hash($data['info']);
Re-encode and calculate the hash:
function create_hash($info)
{
$bencode = new BencodeModel();
return urlencode(sha1($bencode->encode($info)));
}
Font .
It has several forms depending on the purpose.
One of the most common is to use MD5. This is done with the md5_file()
function.
You can also use sha1_file()
which is slower but one gives a result a little better.