How to calculate the hash value of a torrent using Java
How can I calculate the hash value of 开发者_如何学编程a torrent file using Java? Can I calculate it using bencode?
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.
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.
BitTorrent Specification
This should have everything you need, from a more official resource
Can I calculate it using bencode?
No. That is for encoding bittorrent metadata, not actual files.
精彩评论