0

如何使用 Java 计算种子文件的哈希值?我可以使用bencode计算吗?

4

3 回答 3

6

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

注意:此实现适用于大多数 torrent,但不保证 .torrent 文件以 info 键结尾。

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.
于 2010-08-09T01:37:03.360 回答
3

BitTorrent 规范

这应该有你需要的一切,来自更官方的资源

于 2010-08-09T02:00:25.473 回答
1

我可以使用 bencode 计算它吗?

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

于 2010-08-09T02:53:55.237 回答