如何使用Java计算torrent的哈希值

0 java hash bittorrent

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

Bal*_*usC 6

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

注意:此实现适用于大多数种子,但.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.
Run Code Online (Sandbox Code Playgroud)