diff --git a/www/common/crypto.js b/www/common/crypto.js index dd6f826bd..6c5e37aea 100644 --- a/www/common/crypto.js +++ b/www/common/crypto.js @@ -22,12 +22,46 @@ define([ return Nacl.util.encodeUTF8(unpacked); }; + var isBencoded = function (msg) { + return /^\d+:/; + }; + + // this is crap because of bencoding messages... it should go away.... + var splitMessage = function (msg, sending) { + var idx = 0; + var nl; + for (var i = ((sending) ? 0 : 1); i < 3; i++) { + nl = msg.indexOf(':',idx); + idx = nl + Number(msg.substring(idx,nl)) + 1; + } + return [ msg.substring(0,idx), msg.substring(msg.indexOf(':',idx) + 1) ]; + }; + var encrypt = module.exports.encrypt = function (msg, key) { - return encryptStr(msg, key); + if (!isBencoded(msg)) { + return encryptStr(msg, key); + } + var spl = splitMessage(msg, true); + var json = JSON.parse(spl[1]); + // non-patches are not encrypted. + if (json[0] !== 2) { return msg; } + json[1] = encryptStr(JSON.stringify(json[1]), key); + var res = JSON.stringify(json); + return spl[0] + res.length + ':' + res; }; var decrypt = module.exports.decrypt = function (msg, key) { - return decryptStr(msg, key); + if (!isBencoded(msg)) { + return decryptStr(msg, key); + } + var spl = splitMessage(msg, false); + var json = JSON.parse(spl[1]); + // non-patches are not encrypted. + if (json[0] !== 2) { return msg; } + if (typeof(json[1]) !== 'string') { throw new Error(); } + json[1] = JSON.parse(decryptStr(json[1], key)); + var res = JSON.stringify(json); + return spl[0] + res.length + ':' + res; }; var parseKey = module.exports.parseKey = function (str) {