Take the 2-minute tour ×

I'm almost done with my torrent server completely. All I have to do now is find out how .torrent files populate the "pieces" key for the info key.

I currently have this info in my torrent file, encoded in utf-8 format. The hash you see at the end is a has of the file's TITLE, not even close to the bit length I specified before the colon. The bit length for pieces was calculated using (filesize / piece length) * 20, and rounded using round():


8:encoding5:UTF-84:infod6:lengthi71711042e4:name25:Executive Meeting480p.flv

12:piece lengthi128000e6:pieces11205:òOìcØq¬rkÑzÎõyjZee

How do I properly calculate a value for the "pieces" key at the end?

Everytime I try to open it in Transmission, it is read as corrupted.

Do I use fopen(), grab a piece of the file that is "piece length" and create a sha1 hash for each piece until I reach the end of the file?


share|improve this question
@Marc Brown have you looked at the BEncode/BDecode php source maybe this would help, I can post both classes if you like –  Loz Cherone Feb 29 '12 at 21:27
@MarcB I found/was referred that page so many times that I forgot I had three tabs open with it. I understand that they want me to hash each file piece, i.e. file_get_contents() where the maxlen is the size of my piece_length? I think that's all I have to do, but am not sure. –  Marc Brown Feb 29 '12 at 21:57
@LawrenceCherone I have seen the source code and I believe I have to do a while loop where I "sha1" each piece of the file that is the length of "piece length". –  Marc Brown Feb 29 '12 at 21:58
I'm actually making progress. Before I could ready my files as plain text. Now, after I created a while loop that "sha1" the parts of the file using file_get_contents I can no longer open the torrent file using a regular text editor (actually a good thing), but I still have a corrupt file some how... Any tips? Am I missing any thing? Do I need an info hash? –  Marc Brown Feb 29 '12 at 22:27
show 1 more comment

1 Answer

Yes. You read piece size number of bytes from the file, run each piece through SHA-1 independently. The resulting 20 byte SHA-1 digest is your piece, which is put as binary in the pieces string.

If you're using fopen() to read the data, make sure to open the file in binary mode (i.e. specify "b" as the mode). Otherwise your runtime may insert \r whenever it encounters a \n in the byte stream.

You should end up with (filesize + piece_length - 1) / piece_length number of pieces, which multiplied by 20 is the length of your pieces string.

It looks like you're only working with single file torrents. The multi-file torrent case is more complicated. You essentially have to imagine all the files in the torrent being concatenated to form the mapping from a piece to a file and offset.

share|improve this answer
Thanks for the tip. I just read about portability using the binary flag. But, I use "file_get_contents" anyway... –  Marc Brown Mar 16 '12 at 14:04
add comment

Your Answer


