3

I am trying to calculate the info_hash value for a torrent. I read the whole torrent into StringBuffer, then cut it like the following:

d8:announce...info[d6:length...e]e

I can't seem to get the correct hash. Does reading the torrent into a StringBuffer corrupt the byte string at the end? Am I missing something?

public void calculateInfoHash( ){
try{
    int index = rawData.indexOf("4:info") + 6;
    int end = rawData.length() - 1;

    String info = rawData.substring( index , end );

    MessageDigest md = MessageDigest.getInstance( "SHA" );
    md.update( info.getBytes() );
    byte[] digest = md.digest();

    for ( byte b : digest ) {
    // print byte as 2 hex digits with lead 0. 
    //Separate pairs of digits with space
    //System.out.print( "%" );
    System.out.printf( "%02X", b & 0xff );
        }
    System.out.println( );

}catch( Exception e ) { 
    System.out.println( e.toString() );
}
}
Eddie
  • 53,828
  • 22
  • 125
  • 145
Hamza Yerlikaya
  • 49,047
  • 44
  • 147
  • 241
  • 1
    Based on your other question, you have an answer. I'd like to know what it was, as I am trying to do the same thing. – BobMcGee Jun 19 '09 at 21:15
  • The way i solved it was to calculate the hash as i am reading bytes from the file. If you read it in to a string and then calculate it. it never works something gets corrupted. Calculate it as you are reading the file from disk. in your decoder class. – Hamza Yerlikaya Jun 20 '09 at 11:18

2 Answers2

1

I don't know about the correct algorithm in this case, but from a code perspective whenever you call getBytes() on a String you should always specify a character set, otherwise it uses the system default which often isn't what you want. Replace it with:

md.update( info.getBytes("UTF-8") );

and see if that helps.

Marc Novakowski
  • 44,628
  • 11
  • 58
  • 63
-1

You could just grab the source code for Azureus and see how they do it.

OtherDevOpsGene
  • 7,302
  • 2
  • 31
  • 46
  • Hi! Your link redirects from sourceforge.net to vuze.com (Vuze Bittorrent Client which is freeware so I couldn't find any source code for that). Thanks! – eugenes Jul 04 '20 at 23:14
  • Azureus was renamed Vuze many years ago. They closed the source many years ago as well. – OtherDevOpsGene Jul 05 '20 at 20:27