本文介绍了如何使用Java计算torrent的哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I calculate the hash value of a torrent file using Java? Can I calculate it using bencode?

推荐答案

使用。您可以使用获取SHA-1实例。您需要阅读 4:info ,然后收集摘要的字节,直到剩余长度减去一。

Torrent files are hashed using SHA-1. You can use MessageDigest to get a SHA-1 instance. You need to read until 4:info is reached and then gather the bytes for the digest until remaining length minus one.

注意:此实现适用于大多数种子,但.torrent文件不保证以信息键结束。

Note: This implementation works for most torrents, but the .torrent file is not guaranteed to end with the info key.

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.

这篇关于如何使用Java计算torrent的哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 19:08