How to calculate hash?

How do I calculate the hash of a torrent file with PHP?

I already used the Class BEncoded and it worked, but I wanted to know how it works.

Author: Maniero, 2014-12-16

2 answers

A torrent file has a data structure with two higher-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, one uses infohash which is precisely a hash of the encoded data of info. source.

That is, to calculate this infohash you must open the torrent file, interpret its structure and calculate the hash of the relevant part (from what I understood from the above, it is not necessary to decode the whole structure, 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 ends up being necessary to re-encode the relevant part, before applying the hash:

  • Decodes and picks up the relevant part (info):

    $bencode = new BencodeModel();
    $data = $bencode->decode_file($form->fields['filename']->saved_file);
    $hash = $torrentmanager->create_hash($data['info']);
    
  • Re-encodes and calculates the hash:

    function create_hash($info)
    {
        $bencode = new BencodeModel();
        return urlencode(sha1($bencode->encode($info)));
    }
    

Source .

 7
Author: mgibsonbr, 2017-05-23 12:37:28

Has several forms depending on the purpose.

One of the most common is to use MD5. This is done with the function md5_file().

Can also use sha1_file() which is slower but one gives a slightly better result.

 1
Author: Maniero, 2014-12-16 20:56:13