繁体   English   中英

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

[英]How to calculate the hash value of a torrent using Java

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

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.

BitTorrent规范

从更官方的资源中应该可以找到所需的一切

我可以使用bencode进行计算吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM