How to calculate hash?

Asked

Viewed 705 times

5

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

I’ve used the class BEncoded and it worked, but I wanted to know how it works.

  • Do you speak of a hash of the entire file? Or is the hash of the pieces, as required in its structure? (case where the correct one to use would be the SHA-1) Why you want to calculate this hash, what use you have for it?

  • 3

    Magnet:? xt=urn:btih:640FE84C613C17F663551D218689A64E8AEBEABE. I wanted to know how to find out this btih. .

2 answers

7


A torrent file has a data structure with two higher-level keys: announce - identifying the(s) tracker(s) to be used for download - and info - containing the names of the archives and the relevant hashes (of the pieces, I believe, but I’m not sure). To create links "Magnet" is used the infohash which is just a hash of the encoded data of info. Source.

That is, 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 understood above, it is not accurate decode the whole structure, but it is still necessary select it inside the archive).

The detail is that, like the infohash is a hash of the structure coded, and the BencodeModel decodes everything, it is 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-code and compute the hash:

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

Source.

  • I will study this class. Thank you very much.

1

There are several forms depending on the purpose.

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

You can also use the sha1_file() that is slower but one gives a slightly better result.

  • 2

    In fact, this is the correct way to calculate the hash of an entire file, but in the case of Magnet link only a portion of the torrent file needs to be hashed (the constant part that describes the content; the part that describes the trackers by my understanding can change, so that a hash of it does not have much use).

  • 1

    With the additional information seems to be, I only answered what the question said.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.