Compute bittorent info_hash using java

I am trying to calculate the value info_hashfor a torrent. I read the entire stream in StringBufferand then cut it as follows:

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

I can not get the correct hash. Reading torrent in will StringBufferdamage byte string at the end? Did I miss 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() );
}
}
+3
source share
2 answers

I do not know about the correct algorithm in this case, but from the point of view of the code, whenever you call getBytes () on a String, you should always specify a character set, otherwise it uses a system default, which is often not what you want. Replace it with:

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

and see if that helps.

+1
0

Source: https://habr.com/ru/post/1710802/


All Articles