2010-08-09 48 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