Esempio n. 1
0
  /**
   * Bencodes document
   *
   * @param doc Document to be bencoded
   * @return Bencoded string of the provided document
   * @throws LRException BENCODE_FAILED if document cannot be bencoded
   */
  private String bencode(Map<String, Object> doc) throws LRException {
    String text = "";
    String encodedString = "";

    // Bencode the provided document

    try {
      ByteArrayOutputStream s = new ByteArrayOutputStream();
      BencodingOutputStream bencoder = new BencodingOutputStream(s);
      bencoder.writeMap(doc);
      bencoder.flush();
      encodedString = s.toString();
      s.close();

      // Hash the bencoded document
      MessageDigest md;

      md = MessageDigest.getInstance("SHA-256");

      md.update(encodedString.getBytes());
      byte[] mdbytes = md.digest();
      StringBuffer hexString = new StringBuffer();
      for (int i = 0; i < mdbytes.length; i++) {
        String hex = Integer.toHexString(0xFF & mdbytes[i]);
        if (hex.length() == 1) {
          hexString.append('0');
        }
        hexString.append(hex);
      }
      text = hexString.toString();
    } catch (Exception e) {
      throw new LRException(LRException.BENCODE_FAILED);
    }

    return text;
  }