[英]Calculating bittorent info_hash with java
I am trying to calculate the info_hash
value for a torrent. 我正在尝试计算torrent的info_hash
值。 I read the whole torrent into StringBuffer
, then cut it like the following: 我将整个torrent读入StringBuffer
,然后将其剪切如下:
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? 读取torrent到StringBuffer
破坏结尾的字节串吗? 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() );
}
}
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. 在这种情况下我不知道正确的算法,但是从代码的角度来看,每当你在String上调用getBytes()时,你应该总是指定一个字符集,否则它会使用系统默认值,而这通常不是你想要的。 Replace it with: 替换为:
md.update( info.getBytes("UTF-8") );
and see if that helps. 看看是否有帮助。
你可以抓住Azureus的源代码,看看他们是如何做到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.