How can I calculate the hash value of a torrent file using Java? Can I calculate it using bencode?
+3
A:
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.
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.
BalusC
2010-08-09 01:37:03
i tried bytes to convert to hash value but the hash value is different ... for (int i = 0; i < hash.length; i++) { System.out.print(Integer.toString((hash[i] }
Ramesh
2010-08-09 01:54:28
@Ramesh - perhaps the file got mangled when you saved it? Did you (perchance) use a `Reader` or `Scanner` to do that? Anyway, you haven't supplied enough information to allow someone else to figure out what is really going on.
Stephen C
2010-08-09 02:50:41
@Ramesh: you're right, the hash should exist of only the `info` key of the torrent's dictionary. This is located at end of torrent file, bordered by `4:info` and `e`. I've updated the answer accordingly.
BalusC
2010-08-09 04:21:59
ya it works fine now so i can also get the seeds ..Leechers and file size like this????
Ramesh
2010-08-09 04:27:31
+1
A:
Visit that. It'll tell you everything you need on how to create a bittorrent client/server.
Nicholas
2010-08-09 02:00:25
A:
Can I calculate it using bencode?
No. That is for encoding bittorrent metadata, not actual files.
Stephen C
2010-08-09 02:53:55