【发布时间】:2012-11-03 23:03:01
【问题描述】:
根据规范:http://wiki.theory.org/BitTorrentSpecification
info_hash:来自 Metainfo 文件的 info 键值的 urlencoded 20 字节 SHA1 哈希。请注意,根据上面 info 键的定义,该值将是一个经过编码的字典。
torrentMap 是我的字典,我得到 info 键,这是另一个字典,我计算哈希值并 URLencode 它。
但是当我尝试将它发送到跟踪器时,我总是收到一条invalid info_hash 消息。
这是我的代码:
public String GetInfo_hash() {
String info_hash = "";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(torrentMap.get("info"));
byte[] bytes = bos.toByteArray(); //Map => byte[]
MessageDigest md = MessageDigest.getInstance("SHA1");
info_hash = urlencode(md.digest(bytes)); //Hashing and URLEncoding
out.close();
bos.close();
} catch (Exception ex) { }
return info_hash;
}
private String urlencode(byte[] bs) {
StringBuffer sb = new StringBuffer(bs.length * 3);
for (int i = 0; i < bs.length; i++) {
int c = bs[i] & 0xFF;
sb.append('%');
if (c < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(c));
}
return sb.toString();
}
【问题讨论】:
标签: java sha1 bittorrent