How to calculate hash?

5

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.

    
asked by anonymous 16.12.2014 / 21:15

2 answers

7

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 .

    
16.12.2014 / 23:50
1

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.

    
16.12.2014 / 21:49