2010-08-09 59 views

回答

7

使用SHA-1散列Torrent文件。您可以使用MessageDigest来获取SHA-1实例。您需要阅读,直到达到4:info,然后收集摘要的字节,直到剩余长度减1。

File file = new File("/file.torrent"); 
MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); 
InputStream input = null; 

try { 
    input = new FileInputStream(file); 
    StringBuilder builder = new StringBuilder(); 
    while (!builder.toString().endsWith("4:info")) { 
     builder.append((char) input.read()); // It's ASCII anyway. 
    } 
    ByteArrayOutputStream output = new ByteArrayOutputStream(); 
    for (int data; (data = input.read()) > -1; output.write(data)); 
    sha1.update(output.toByteArray(), 0, output.size() - 1); 
} finally { 
    if (input != null) try { input.close(); } catch (IOException ignore) {} 
} 

byte[] hash = sha1.digest(); // Here's your hash. Do your thing with it. 
+0

我试图字节转换为哈希值,但哈希值是不同... \t \t对(INT I = 0; I Ramesh 2010-08-09 01:54:28

+0

@Ramesh - 当你保存文件时,文件可能已经被破坏了?你有没有使用'Reader'或'Scanner'来做到这一点?无论如何,你还没有提供足够的信息来让其他人知道真正发生了什么。 – 2010-08-09 02:50:41

+0

@Ramesh:你说得对,散列应该只存在于torrent字典的'info'键。这是位于torrent文件的末尾,以'4:info'和'e'为边界。我已经相应地更新了答案。 – BalusC 2010-08-09 04:21:59

3

BitTorrent Specification

这应该有你需要的一切,从使用bencode一个更正式的资源

+0

作为Nicholas I链接的官方说明的补充,我还会推荐inofficial规范维基发现在:https://wiki.theory.org/BitTorrentSpecification – Encombe 2015-02-04 18:01:43

1

我能计算呢?

不是。这是用于编码bittorrent元数据,而不是实际文件。

+0

我可以从洪流文件使用bencode提取元数据? – Ramesh 2010-08-09 03:23:55

+0

我不知道。但是,这与你在这里问的问题完全不同。你为什么不先把注意力放在这个上面......并按照上面的要求提供更多的信息。 – 2010-08-09 03:58:35