注意:此实现适用于大多数 torrent,但 .torrent 文件不保证以 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.
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.
发布评论
评论(3)
Torrent 文件使用 SHA-1 进行哈希处理。您可以使用
MessageDigest
< /a> 获取 SHA-1 实例。您需要读取直到达到4:info
,然后收集摘要的字节,直到剩余长度减一。注意:此实现适用于大多数 torrent,但 .torrent 文件不保证以 info key 结尾。
Torrent files are hashed using SHA-1. You can use
MessageDigest
to get a SHA-1 instance. You need to read until4: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.
BitTorrent 规范
这应该包含您需要的一切,来自更官方的资源
BitTorrent Specification
This should have everything you need, from a more official resource
不。那是为了编码 BitTorrent 元数据,而不是实际文件。
No. That is for encoding bittorrent metadata, not actual files.