Beispiel #1
0
zlib.deflateRaw(input, function (err, zip) {
  zlib.inflateRaw(zip, function (err, str) {
    console.log('#', JSON.stringify(str.toString()));
    console.log('#', JSON.stringify(input));
    console.log(str.toString() == input ? 'ok' : 'not ok');
  })
})
Beispiel #2
0
function getSamlRequest(samlRequest, callback) {
  if (!samlRequest) return callback();

  try {
    var input = new Buffer(samlRequest, 'base64');
    
    if (input[0] === 60) {  // open tag
      // content is just encoded, not zipped
      var xml = new xmldom.DOMParser().parseFromString(input.toString());
      if (!xml || !xml.documentElement) {
        return callback(new Error('Invalid SAML Request'));
      }

      callback(null, xml);
    } else {
      zlib.inflateRaw(input, function(err, buffer) {
        if (err) return callback(err);

        var xml = new xmldom.DOMParser().parseFromString(buffer.toString());
        if (!xml || !xml.documentElement) {
          return callback(new Error('Invalid SAML Request'));
        }

        callback(null, xml);
      });
    }
  } catch(e) {
    callback(e);
  }
}
Beispiel #3
0
 zlib.inflate(bufferAll, function (err, result) {
   if (err && err.code === 'Z_DATA_ERROR') {
     zlib.inflateRaw(bufferAll, onDecode);
   } else {
     onDecode(err, result);
   }
 });
Beispiel #4
0
 zlib.inflateRaw(data.slice(2, 2+headers_length), function(error, buff) {
     buff.toString().split("\n").forEach(function(line) {
         var pos = line.indexOf(':');
         if (pos > 0) {
             var key = line.substring(0, pos);
             var value = line.substring(pos+1);
             if (key == 'G-Method') {
                 request.method = value;
             } else if (key == 'G-Url') {
                 request.url = value;
             } else if (key.indexOf('G-') == 0) {
                 request.kwargs[key.substring(2)] = value;
             } else {
                 request.headers[key] = value;
             }
         }
     });
     if (request.headers.hasOwnProperty('Content-Encoding')
         && request.headers['Content-Encoding'] == 'deflate') {
         zlib.inflateRaw(request.body, function(error, buff) {
             request.body = buff;
             request.headers['Content-Length'] = request.body.length.toString();
             delete request.headers['Content-Encoding'];
             callback(request);
         });
     } else {
         callback(request);
     }
 });
/**
 * Decompresses a byte array using the decompression method passed by type.
 * It supports gunzip and deflate
 * */
function decompress(body, type) {
    var deferred = new Deferred();

    if (type === 'gzip') {
        zlib.gunzip(body, function (err, data) {
            if (!err) {
                deferred.resolve({
                    body: data.toString(charset),
                    compression: 'gzip'
                });
            } else {
                deferred.reject('Error found: can\'t gunzip content ' + err);
            }
        });
    } else if (type === 'deflate') {
        zlib.inflateRaw(body, function (err, data) {
            if (!err) {
                deferred.resolve({
                        body: data.toString(charset),
                        compression: 'deflate'}
                );
            } else {
                deferred.reject('Error found: can\'t deflate content' + err);
            }
        });
    } else {
        process.nextTick(function () {
            deferred.reject("Unknown content encoding: " + type);
        });
    }

    return deferred.promise;
}
    it('should have SAMLRequest querystring', function(done){
      expect(r.headers.location.split('?')[0])
            .to.equal(server.identityProviderUrl);
      var querystring = qs.parse(r.headers.location.split('?')[1]);
      expect(querystring).to.have.property('SAMLRequest');
      var SAMLRequest = querystring.SAMLRequest;

      zlib.inflateRaw(new Buffer(SAMLRequest, 'base64'), function (err, buffer) {
        if (err) return done(err);
        var request = buffer.toString();
        var doc = new xmldom.DOMParser().parseFromString(request);

        expect(doc.documentElement.getAttribute('Protocol'))
          .to.equal('urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST');

        expect(doc.documentElement.getAttribute('Version'))
          .to.equal('3.0');

        expect(doc.documentElement.getAttribute('Foo'))
          .to.equal('123');

        expect(doc.documentElement.getAttribute('Issuertico'))
          .to.equal('https://auth0-dev-ed.my.salesforce.com');

        done();
      });

    });
    it('should have SAMLRequest querystring', function(done){
      expect(r.headers.location.split('?')[0])
            .to.equal(server.identityProviderUrl);
      var querystring = qs.parse(r.headers.location.split('?')[1]);
      expect(querystring).to.have.property('SAMLRequest');
      var SAMLRequest = querystring.SAMLRequest;

      zlib.inflateRaw(new Buffer(SAMLRequest, 'base64'), function (err, buffer) {
        if (err) return done(err);
        var request = buffer.toString();
        var doc = new xmldom.DOMParser().parseFromString(request);

        expect(doc.documentElement.getAttribute('ProtocolBinding'))
          .to.equal('urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST');

        expect(doc.documentElement.getAttribute('Version'))
          .to.equal('2.0');

        expect(doc.documentElement.getElementsByTagName('saml:Issuer')[0]
                                  .getAttribute('xmlns:saml'))
          .to.equal('urn:oasis:names:tc:SAML:2.0:assertion');

        done();
      });

    });
Beispiel #8
0
 helper.runInTransaction(agent, function() {
   zlib.inflateRaw(new Buffer(DEFLATED_RAW, 'base64'), function(err, data) {
     t.notOk(err, 'should not error')
     t.equal(data.toString(), CONTENT)
     verifySegments(t, agent, 'zlib.inflateRaw')
   })
 })
Beispiel #9
0
            spidex.get(url, function(html, status) {
                zlib.inflateRaw(new Buffer(html, "binary"), function(err, buff) {
                    if(err) return callback(err);
                    html = buff.toString("utf8");

                    callback(undefined, html);
                });
            }, {
 zopfli.deflate(buffer).then(function(result) {
   zlib.inflateRaw(result, function(err, result) {
     if (!err) {
       assert.equal(result.toString(), buffer.toString());
     }
     done(err);
   });
 });
Beispiel #11
0
            res.end = function () {

                var _instrumentJS = function (str, options) {
                    options.source = "ExternalJS";
                    options.origin = {};
                    options.origin.file = req.url;
                    return instrument.instrument(str, options).toString();
                };

                var _instrumentHTML = function (str, options) {
                    options.origin = {
                        file: req.url
                    }
                    return instrument_html.instrument_html(str, options);
                };

                var processContent = function (content) {
                    res.removeHeader("Content-Encoding");
                    if (_isJS) {
                        processedContent = _instrumentJS(content, options);
                    } else if (_isHTML) {
                        processedContent = _instrumentHTML(content, options);
                    } else {
                        processedContent = content;
                    }
                    
                    //finish up
                    _headers['content-length'] = Buffer.byteLength(processedContent, 'utf8');
                    _writeHead.call(res, _code, _headers);
                    _write.call(res, processedContent);
                    _end.apply(res, []);
                };
                var bufferToString = function (buffer) {
                    // console.log(buffer[0].toString(16), buffer[1].toString(16));
                    if(buffer.length > 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) {
                        return iconv.decode(buffer, "utf16-le");
                    } else {
                        // assume it is utf-8
                        return iconv.decode(buffer, "utf8");
                    }
                }

                if (_process) {
                    if (this.getHeader("Content-Encoding") === "gzip") {
                        zlib.unzip(_content, function(err, buffer) {
                            processContent(bufferToString(buffer));
                        });
                    } else if (this.getHeader("Content-Encoding") === "deflate") {
                        zlib.inflateRaw(_content, function(err, buffer) {
                            processContent(bufferToString(buffer));
                        });
                    } else {
                        processContent(bufferToString(_content));
                    }
                } else {
                    _end.apply(res, []);
                }
            };
Beispiel #12
0
zlib.deflateRaw(input, function(err,buffer){
	if(!err){
		console.log("defalteRaw (%s):", buffer.length, buffer.toString('base64'));
		zlib.inflateRaw(buffer, function(err,buffer){
			if(!err){
				console.log("inflate (%s):", buffer.length, buffer.toString());
			}
		});
	}
});
Beispiel #13
0
    zlib.deflateRaw(str, function(e,b) {
      expect(e).toBeFalsy();
      expect(b.toString('base64')).toBe(encoded);

      zlib.inflateRaw(b, function(ee, bb) {
        expect(ee).toBeFalsy();
        expect(bb.toString()).toBe(str);
        helper.testComplete(true);
      });
    });
Beispiel #14
0
 return new Promise(function(resolve, reject) {
   zlib.inflateRaw(new Buffer(jwe.plaintext), function(err, data) {
     if (err) {
       reject(err);
     }
     else {
       jwe.payload = jwe.plaintext = data;
       resolve(jwe);
     }
   });
 });
Beispiel #15
0
hzip.updateEntry("testDir/中文test.txt",fs.readFileSync("./test.txt"),function(err,buffer){
	if(err) {
		console.log(err);
		return;
	}
	if(fs.existsSync("./test2.zip") === true) fs.unlinkSync("./test2.zip");
	fs.writeFileSync("./test2.zip",buffer);
	
	//解压文件
	var entry = hzip.getEntry("testDir/test.txt");
	zlib.inflateRaw(entry.cfile,function(err,buf){
		console.log(buf.toString());
	});
});
  var next = function next(err) {
    if (err) {
      return cb(err);
    }

    if (!fields.length) {
      return cb(null, data);
    }

    var field = fields.shift();

    if (!uri.query[field[0]]) {
      return next();
    }

    var xml = Buffer(uri.query[field[0]], "base64");

    zlib.inflateRaw(xml, function(err, xml) {
      if (err) {
        return next(err);
      }

      try {
        xml = new xmldom.DOMParser().parseFromString(xml.toString("utf8"));
      } catch (e) {
        return next(e);
      }

      if (!xml) {
        return next(Error("couldn't parse " + field[0] + " field"));
      }

      try {
        var obj = protocol.fromDocument(xml.documentElement);
      } catch (e) {
        return next(e);
      }

      if (!obj) {
        return next(Error("couldn't figure out how to use a " + xml.documentElement.tagName + " to construct an object"));
      }

      data[field[1]] = xml;
      data[field[2]] = obj;

      return next();
    });
  };
Beispiel #17
0
function getSamlRequest(samlRequest, callback) {
  if (!samlRequest) return callback();

  var input = new Buffer(samlRequest, 'base64');
  if (input[0] === 60) {  // open tag
    // content is just encoded, not zipped
    var xml = new xmldom.DOMParser().parseFromString(input.toString());
    callback(null, xml);
  } else {
    zlib.inflateRaw(input, function(err, buffer) {
      if (err) return callback(err);

      var xml = new xmldom.DOMParser().parseFromString(buffer.toString());
      callback(null, xml);
    });
  }
}
Beispiel #18
0
  collector.on('message', function(msg) {
    zlib.inflateRaw(msg, function(err, res) {
      if (err) {
        console.log('ERR: ' + err)
      } else {
        var obj = JSON.parse(res)
        var id
        if (obj.nodeinfo) {
          id = obj.nodeinfo.node_id
        } else if (obj.statistics) {
          id = obj.statistics.node_id
        } else if (obj.neighbours) {
          id = obj.neighbours.node_id
        } else return

        api.receiverCallback(id, obj, receiverId)
      }
    })
  })
Beispiel #19
0
SAML.prototype.validateLogoutResponse = function(samlResponse, callback) {
	const self = this;

	const compressedSAMLResponse = new Buffer(samlResponse, 'base64');
	zlib.inflateRaw(compressedSAMLResponse, function(err, decoded) {

		if (err) {
			if (Meteor.settings.debug) {
				console.log(err);
			}
		} else {
			const parser = new xml2js.Parser({
				explicitRoot: true
			});
			parser.parseString(decoded, function(err, doc) {
				const response = self.getElement(doc, 'LogoutResponse');

				if (response) {
					// TBD. Check if this msg corresponds to one we sent
					const inResponseTo = response.$.InResponseTo;
					if (Meteor.settings.debug) {
						console.log(`In Response to: ${ inResponseTo }`);
					}
					const status = self.getElement(response, 'Status');
					const statusCode = self.getElement(status[0], 'StatusCode')[0].$.Value;
					if (Meteor.settings.debug) {
						console.log(`StatusCode: ${ JSON.stringify(statusCode) }`);
					}
					if (statusCode === 'urn:oasis:names:tc:SAML:2.0:status:Success') {
						// In case of a successful logout at IDP we return inResponseTo value.
						// This is the only way how we can identify the Meteor user (as we don't use Session Cookies)
						callback(null, inResponseTo);
					} else {
						callback('Error. Logout not confirmed by IDP', null);
					}
				} else {
					callback('No Response Found', null);
				}
			});
		}

	});
};
Beispiel #20
0
SAML.prototype.validateLogoutResponse = function(samlResponse, callback) {
	const self = this;
	const compressedSAMLResponse = new Buffer(samlResponse, 'base64');
	zlib.inflateRaw(compressedSAMLResponse, function(err, decoded) {
		if (err) {
			debugLog(`Error while inflating. ${ err }`);
		} else {
			debugLog(`constructing new DOM parser: ${ Object.prototype.toString.call(decoded) }`);
			debugLog(`>>>> ${ decoded }`);
			const doc = new xmldom.DOMParser().parseFromString(array2string(decoded), 'text/xml');
			if (doc) {
				const response = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'LogoutResponse')[0];
				if (response) {

					// TBD. Check if this msg corresponds to one we sent
					let inResponseTo;
					try {
						inResponseTo = response.getAttribute('InResponseTo');
						debugLog(`In Response to: ${ inResponseTo }`);
					} catch (e) {
						if (Meteor.settings.debug) {
							debugLog(`Caught error: ${ e }`);
							const msg = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusMessage');
							debugLog(`Unexpected msg from IDP. Does your session still exist at IDP? Idp returned: \n ${ msg }`);
						}
					}

					const statusValidateObj = self.validateStatus(doc);

					if (statusValidateObj.success) {
						callback(null, inResponseTo);
					} else {
						callback('Error. Logout not confirmed by IDP', null);

					}
				} else {
					callback('No Response Found', null);
				}
			}
		}

	});
};
collector.on('message', (msg, rinfo) => {
  console.log("Found Node");
  zlib.inflateRaw(msg, (err,res) => {
    if (err) {
      console.log('ERR: ' + err)
    } else {
      var obj = JSON.parse(res)
      var id

      if (obj.nodeinfo) {
        id = obj.nodeinfo.node_id
      } else if (obj.statistics) {
        id = obj.statistics.node_id
      } else if (obj.neighbours) {
        id = obj.neighbours.node_id
      } else return

      if (!raw[id]) {
        raw[id] = {}
        raw[id].firstseen = new Date().toISOString()
      }

      if (obj.nodeinfo)
        raw[id].nodeinfo = obj.nodeinfo
      else if (obj.statistics)
        raw[id].statistics = obj.statistics
      else if (obj.neighbours)
        raw[id].neighbours = obj.neighbours
      raw[id].lastseen = new Date().toISOString()
      if (obj.statistics || obj.neighbours && !raw[id].nodeinfo) {
	if(sitecode == '' || raw[id].nodeinfo.system.site_code == sitecode){
	  console.log("ja");
          retrieve('nodeinfo', rinfo.address)
        }else{
	  console.log("nein");
	}
      }

    }
  })
})
Beispiel #22
0
SAML.prototype.validateLogoutRequest = function(samlRequest, callback) {
	const compressedSAMLRequest = new Buffer(samlRequest, 'base64');
	zlib.inflateRaw(compressedSAMLRequest, function(err, decoded) {
		if (err) {
			debugLog(`Error while inflating. ${ err }`);
			return callback(err, null);
		}

		debugLog(`LogoutRequest: ${ decoded }`);
		const doc = new xmldom.DOMParser().parseFromString(array2string(decoded), 'text/xml');
		if (!doc) {
			return callback('No Doc Found');
		}

		const request = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'LogoutRequest')[0];
		if (!request) {
			return callback('No Request Found');
		}

		try {
			const sessionNode = request.getElementsByTagName('samlp:SessionIndex')[0];
			const nameIdNode = request.getElementsByTagName('saml:NameID')[0];

			const idpSession = sessionNode.childNodes[0].nodeValue;
			const nameID = nameIdNode.childNodes[0].nodeValue;

			return callback(null, { idpSession, nameID });

		} catch (e) {
			debugLog(`Caught error: ${ e }`);

			const msg = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusMessage');
			debugLog(`Unexpected msg from IDP. Does your session still exist at IDP? Idp returned: \n ${ msg }`);

			return callback(e, null);
		}
	});
};
Beispiel #23
0
        new Promise((fulfill, rejectParsing) => {
          if (resDataStream) {
            fulfill(resDataStream);
          } else {
            const serverResData = Buffer.concat(resDataChunks);
            const originContentLen = util.getByteSize(serverResData);
            // remove gzip related header, and ungzip the content
            // note there are other compression types like deflate
            const contentEncoding = resHeader['content-encoding'] || resHeader['Content-Encoding'];
            const ifServerGzipped = /gzip/i.test(contentEncoding);
            const isServerDeflated = /deflate/i.test(contentEncoding);
            const isBrotlied = /br/i.test(contentEncoding);

            /**
             * when the content is unzipped, update the header content
             */
            const refactContentEncoding = () => {
              if (contentEncoding) {
                resHeader['x-anyproxy-origin-content-encoding'] = contentEncoding;
                delete resHeader['content-encoding'];
                delete resHeader['Content-Encoding'];
              }
            }

            // set origin content length into header
            resHeader['x-anyproxy-origin-content-length'] = originContentLen;

            // only do unzip when there is res data
            if (ifServerGzipped && originContentLen) {
              refactContentEncoding();
              zlib.gunzip(serverResData, (err, buff) => {
                if (err) {
                  rejectParsing(err);
                } else {
                  fulfill(buff);
                }
              });
            } else if (isServerDeflated && originContentLen) {
              refactContentEncoding();
              zlib.inflateRaw(serverResData, (err, buff) => {
                if (err) {
                  rejectParsing(err);
                } else {
                  fulfill(buff);
                }
              });
            } else if (isBrotlied && originContentLen) {
              refactContentEncoding();

              try {
                // an Unit8Array returned by decompression
                const result = brotliTorb.decompress(serverResData);
                fulfill(Buffer.from(result));
              } catch (e) {
                rejectParsing(e);
              }
            } else {
              fulfill(serverResData);
            }
          }
        }).then((serverResData) => {
Beispiel #24
0
module.exports.parseSamlRequest = function(req, samlRequest, type, options, callback) {
  function checkSignature(xml, cb) {
    var opts = {
      signingCert: options.signingCert,
      thumbprints: options.thumbprints,
      deflate: !!req.query.Signature,
      relayState: options.relayState
    };

    try {
      validateSignature(req, type, xml, opts);
      return cb(null, xml);
    } catch (e) {
      return cb(e);
    }
  }

  /**
   * Check if the issuer signing credentials are set correctly.
   * If they aren't and the IdP passed a `getCredentials` function
   * will use it to configure the issuer credentials to be used when
   * validating the incoming SAML Request
   * @xml {Object}   The SAML Request as a DOM Object
   * @cb  {Function} The callback. Will return a boolean if the SAML Request has to get its signature verified
   */
  function configureSigningCredentials(xml, cb) {
    if (options.signingCert || options.thumprints) { return cb(null, true) };

    if (!options.getCredentials) {
      return cb(null, false);
    }

    var issuer, sessionIndex, nameId;
    var issuerNode = xpath.select(constants.ELEMENTS[type].ISSUER_PATH, xml);

    if (issuerNode && issuerNode.length > 0) {
      issuer = issuerNode[0].textContent;
    }

    // If LogoutRequest, we should check sessionIndex too    
    if (constants.ELEMENTS[type].SESSION_INDEX_PATH){
      var sessionIndexNode = xpath.select(constants.ELEMENTS[type].SESSION_INDEX_PATH, xml);
      if (sessionIndexNode && sessionIndexNode.length > 0) {
        sessionIndex = sessionIndexNode[0].textContent;
      }
    }

    // If LogoutRequest, we should check sessionIndex too    
    if (constants.ELEMENTS[type].NAME_ID){
      var nameIdNode = xpath.select(constants.ELEMENTS[type].NAME_ID, xml);
      if (nameIdNode && nameIdNode.length > 0) {
        nameId = nameIdNode[0].textContent;
      }
    }

    if (!issuer && !sessionIndex && !nameId){
      return cb(null, false);
    }

    options.getCredentials(issuer, sessionIndex, nameId, function (err, credentials) {
      if (!credentials){
        return cb(null, false);
      }

      options.signingCert = credentials.cert;
      options.thumbprints = credentials.thumbprints;
      return cb(null, true);
    });
  }

  if (!samlRequest) return callback();

  try {
    var input = new Buffer(samlRequest, 'base64');

    if (input[0] === 60) {  // open tag
      // content is just encoded, not zipped
      var xml = new xmldom.DOMParser().parseFromString(input.toString());
      if (!xml || !xml.documentElement) {
        return callback(new Error('Invalid SAML Request'));
      }

      configureSigningCredentials(xml, function (err, shouldValidate) {
        if (!shouldValidate) {
          return callback(null, xml);
        }
        checkSignature(xml, callback);
      });

    } else {
      zlib.inflateRaw(input, function(err, buffer) {
        if (err) { return callback(err); }

      try{
        var xml = new xmldom.DOMParser().parseFromString(buffer.toString());
      }
      catch(e) { 
        return callback(new Error(e));
      }

        if (!xml || !xml.documentElement) {
          return callback(new Error('Invalid SAML Request'));
        }

        configureSigningCredentials(xml, function (err, shouldValidate) {
          if (!shouldValidate) {
            return callback(null, xml);
          }
          checkSignature(xml, callback);
        });
      });
    }
  } catch(e) {
    callback(e);
  }
};
Beispiel #25
0
	it("inflate (from file)", function() {
		var f1 = fs.openTextStream('./zlib_files/deflate');
		var f2 = fs.openTextStream('./zlib_files/original.js');
		assert.equal(zlib.inflateRaw(f1.read()).toString(), f2.read().toString());
	});
// Include the zlib module.
var z = require('zlib');
// Make a new buffer object from base64 encoded string.
var b = new Buffer('3ZJJTgMxEEX3fYp/BDrM7CAhYZGQiPQFrLhIl/AQld0JuT12cwBkxNgrW7b8670vLx1iS6hDhFZH+GeMW+EQrQqVPSJKRzB+TwjkIqKHpZvqFislUVhvCeygsCIlaISoqpbvgSOnCwKbg0fTSTSESboLlUrP1cdTTqVoSpveYirkNi0eyIVPzz2LbcHcqe8EY2UMuy3uWHT4QpTzMhROBzNvNDk8JZzwvXAXRXBrfsWMKFDKmqtjAvpp3ssyXtonrPVBuZDS1ge2NjP/vsZVkcY9b9uIhWKdNRZsXnqLvyp3XST3yI4SqGYKmCi3ycD/TLg+KTJuEtXcS+82J7XLxENooS771KYXWfGOJOQlIw+1mlFRNfUIE+mszcX0m155+H29AQ==', 'base64');
// Use zlib to decompress. Don't do any error checking (the e variable is ignored).
z.inflateRaw(b, function(e, s) {
	//Write to stdout.
	console.log(s.toString());
});

/* The above can be chained instead of using variables.
 * Also we can omit semicolons.
 * And we can omit the "new" keyword when creating the Buffer.
 So it looks like this:
 require('zlib').inflateRaw(Buffer('3ZJJTgMxEEX3fYp/BDrM7CAhYZGQiPQFrLhIl/AQld0JuT12cwBkxNgrW7b8670vLx1iS6hDhFZH+GeMW+EQrQqVPSJKRzB+TwjkIqKHpZvqFislUVhvCeygsCIlaISoqpbvgSOnCwKbg0fTSTSESboLlUrP1cdTTqVoSpveYirkNi0eyIVPzz2LbcHcqe8EY2UMuy3uWHT4QpTzMhROBzNvNDk8JZzwvXAXRXBrfsWMKFDKmqtjAvpp3ssyXtonrPVBuZDS1ge2NjP/vsZVkcY9b9uIhWKdNRZsXnqLvyp3XST3yI4SqGYKmCi3ycD/TLg+KTJuEtXcS+82J7XLxENooS771KYXWfGOJOQlIw+1mlFRNfUIE+mszcX0m155+H29AQ==', 'base64'), function(e, o) {
 	console.log(o.toString())
 })

The base64 encode string can be created like this:
const zlib = require('zlib');
const fs = require('fs');

fs.readFile('12daysofchristmas.txt', 'utf8', function(err_fs, data){
	if (err_fs) {
		console.log(err_fs);
	} else {
		zlib.deflateRaw(data, function(err_zlib, buf){
			if (err_zlib) {
				console.log(err_zlib);
			} else {
				var s = buf.toString('base64');
Beispiel #27
0
SAML2Strategy.prototype.handleRedirect = function handleRedirect(req, res, next) {
  if (!req.query || (!req.query.SAMLRequest && !req.query.SAMLResponse)) {
    return next(Error("no SAML fields found in query"));
  }

  if (req.query.SAMLRequest && req.query.SAMLResponse) {
    return next(Error("too many SAML fields found in query"));
  }

  var key = req.query.SAMLRequest ? "SAMLRequest" : "SAMLResponse";

  var data;
  try {
    data = Buffer(req.query[key], "base64");
  } catch (e) {
    return next(e);
  }

  zlib.inflateRaw(data, function(err, inflated) {
    if (err) {
      return next(err);
    }

    var xml;
    try {
      xml = (new xmldom.DOMParser()).parseFromString(inflated.toString("utf8"));
    } catch (e) {
      return next(e);
    }

    if (!xml) {
      return next(Error("couldn't parse XML"));
    }

    if (this.idp.certificate) {
      var valid;
      try {
        valid = this.idp.verify(xml);
      } catch (e) {
        return next(e);
      }

      if (!valid) {
        return next(Error("signature for IDP response was invalid"));
      }
    }

    var message;
    try {
      message = saml2.Protocol.fromXML(xml.documentElement);
    } catch (e) {
      return next(e);
    }

    if (!message) {
      return next(Error("couldn't construct message from tag: " + xml.documentElement.localName));
    }

    req.samlMessage = message;

    return next();
  });
};
Beispiel #28
0
 unzip: function(str, cb){
     if ('string' !== typeof(str) || '' === str) return cb('unzip err: no payload: '+typeof(str))
     zlib.inflateRaw(new Buffer(str, 'base64'), function(err, buf){
         cb(err, err || buf.toString())
     })
 },
Beispiel #29
0
var inflate = function(data, isCgBI, callback) {
  return isCgBI ? zlib.inflateRaw(new Buffer(data), callback) : zlib.inflate(new Buffer(data), callback);
};
Beispiel #30
0
 decode : function(buffer,cb)
 {
     zip.inflateRaw(buffer,cb);//解压缩
 }