node.jsgeturlencodebittorrent

Encoding info_hash for request torrent tracker


I would like to interact with a torrent tracker in Node.js. So I calculate the info_hash and I get the good one : 7cd350e5a70f0a61593e636543f9fc670ffa8a4d

But to be send to the tracker it have to be urlencoded. The problem is I don't know how to do it to get the right encoded value which is %7c%d3P%e5%a7%0f%0aaY%3eceC%f9%fcg%0f%fa%8aM

I doesn't know how to get this value, because it doesn't follow the %nnformat

I tried with encodeURIComponent and querystring, but I didn't get the right string.


Solution

  • Here's one solution that matches the expected output (including capitalization):

    var h = '7cd350e5a70f0a61593e636543f9fc670ffa8a4d';
    h = h.replace(/.{2}/g, function(m) {
      var v = parseInt(m, 16);
      if (v <= 127) {
        m = encodeURIComponent(String.fromCharCode(v));
        if (m[0] === '%')
          m = m.toLowerCase();
      } else
        m = '%' + m;
      return m;
    });
    console.log(h);
    
    // outputs: %7c%d3P%e5%a7%0f%0aaY%3eceC%f9%fcg%0f%fa%8aM