且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-03 20:57:34

使用 SHA-对Torrent文件进行哈希处理1 。您可以使用 MessageDigest 获取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.