views:

148

answers:

4

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
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
@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
@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
ya it works fine now so i can also get the seeds ..Leechers and file size like this????
Ramesh
+1  A: 

BitTorrent RFC

Visit that. It'll tell you everything you need on how to create a bittorrent client/server.

Nicholas
A: 

Can I calculate it using bencode?

No. That is for encoding bittorrent metadata, not actual files.

Stephen C
can i extract meta datas from the torrent file using bencode???
Ramesh
I've no idea. But that's a completely different question to the one you asked here. Why don't you focus on this one first ... and provide more information as requested above.
Stephen C
A: 

focus on meta search..

jay