Beispiel #1
0
(function(){
	var supportedAlgorithms = crypto.getHashes();
	var supportedOutputEncodings = ['base64', 'binary', 'hex'];
	
	var defaults = {
		algorithm: 'sha1',
		outputEncoding: 'base64'
	};

	module.exports = function(value, options){
		if(typeof options !== 'object')
			options = {};
		
		options = util.extend(options, defaults);

		if(supportedAlgorithms.indexOf(options.algorithm) === -1)
			throw new Error('Hash algorithm \'' + options.algorithm + '\' not supported.');

		if(supportedOutputEncodings.indexOf(options.outputEncoding) === -1)
			throw new Error('Hash output encoding \'' + options.outputEncoding + '\' not supported.');

		var shasum = crypto.createHash(options.algorithm);
		shasum.update(value);
		
		var digest = shasum.digest(options.outputEncoding);
		return digest;
	};
})();
Beispiel #2
0
module.exports = function()
{
	var crypto = require('crypto');
	var Hash = require('./Hash');

	// Silently abort if the adler32 algorithm is already supported by the
	// crypto module.
	if (crypto.getHashes().indexOf('adler32') != -1)
		return;

	crypto.getHashes = function()
	{
		return this().concat(['adler32']);
	}
	.bind(crypto.getHashes.bind(crypto));

	crypto.createHash = function(algorithm)
	{
		if (algorithm === 'adler32')
			return new Hash();
		else
			return this(algorithm);
	}
	.bind(crypto.createHash.bind(this));
};
Beispiel #3
0
exports.supportedHash = (function () {
  if (!crypto.getCiphers) {
    return canCreateHash
  }

  var cryptoHashes = crypto.getHashes()

  return function supportedHash(val) {
    return cryptoHashes.indexOf(val) !== -1
  }
}())
function HASH(config) {
  this.cleartext = config.cleartext
  this.encoding = config.encoding

  this.algorithms = crypto.getHashes()

  this.hashes = crypto.getHashes().map(function (algorithm, index) {
    return {
      me: crypto.createHash(algorithm),
      index: index,
      algorithm: algorithm,
      encrypted: ''
    }
  })

  this.log = fs.openSync('log/08.hash.update.log', 'w')

  this.ergodic_init()
  this.ergodic_start(0)
}
Beispiel #5
0
doudou.task('hash', function(doudou, hashType) {
    if(typeof hashType == "undefined") {
        hashType = 'md5';
        console.warn("Undefined hash type @" + doudou._stackTrace + ". Will use 'md5' as default.");
    }
    if(crypto.getHashes().indexOf(hashType) == -1)
        return doudou._error(new Error('Unkown hash algorithm "'+hashType+'"'));
    tmp.file(tmpFileCreated.bind(doudou, hashType));

    // wait for this doudou to complete
    return doudou;
}, {
  it("various hashes in crypto.getHashes() should be supported", function() {
    var hashes = ['sha1', 'md5'];

    if (crypto.getHashes) {
      // take all hashes from crypto.getHashes() starting with MD or SHA
      hashes = crypto.getHashes().filter(RegExp.prototype.test.bind(/^(md|sha)/i));
    }

    var obj = {randomText: 'bananas'};

    for (var i = 0; i < hashes.length; i++) {
      assert.ok(hash(obj, {algorithm: hashes[i]}), 'Algorithm ' + hashes[i] + ' should be supported');
    }
  });
/**
 * Generate a hash based on the string passed to the function.
 * @param   str     {string}
 * @param   length  {int}
 * @returns {string}
 */
function generateHash(str, length)
{
    length = (length === parseInt(length)) ? length : 8;
    var preferredCiphers = ['md4','md5'];

    for(var i = 0; i < preferredCiphers.length; i++) {
        if(crypto.getHashes().indexOf(preferredCiphers[i]) !== -1) {
            var hash = crypto.createHash(preferredCiphers[i])
                .update(str)
                .digest('hex')
                .slice(0,length);
        }
    }
    return hash || uuid(length);
}
Beispiel #8
0
exports.hash = (obj, options) => {
  options = options || {};
  const alg = options.alg || 'sha256';
  const enc = options.enc || 'hex';
  const coerce = typeof options.coerce == 'undefined' ? true : options.coerce;
  const sort = typeof options.sort == 'undefined' ? true : options.sort;

  if (~crypto.getHashes().indexOf(alg)) {
    const sorted = exports.sortedObjectString(obj, {coerce, sort});
    return crypto.createHash(alg)
      .update(sorted)
      .digest(enc);
  } else {
    throw new Error(`Algorithm ${alg} not supported by "ctypto" module`);
  }
};
Beispiel #9
0
/// <summary>
/// 	Tries to set the best hash algorithm.
/// 	Synchronous.
/// </summary>
function setBestAvailableHashAlgorithm() {
	var goodHashAlgortihms = ['sha512WithRSAEncryption', 'rsa-sha512', 'sha512', 'sha256WithRSAEncryption', 'rsa-sha256', 'sha256'];
	var availableHashAlgorithms = Crypto.getHashes();

	var i = goodHashAlgortihms.length;
	var index;
	while (i-- > 0) {
		index = availableHashAlgorithms.indexOf(goodHashAlgortihms[i]);
		if (index !== -1) {
			HASH_ALGORITHM = availableHashAlgorithms[index];
		}
	}

	if (!HASH_ALGORITHM) {
		throw new Error('No good hash algorithm found');
	}
}
Beispiel #10
0
// Internals
function validate(object, options){
  var hashes = crypto.getHashes ? crypto.getHashes() : ['sha1', 'md5'];
  var encodings = ['buffer', 'hex', 'binary', 'base64'];

  if(typeof object === 'undefined') {
    throw new Error('Object argument required.');
  }

  if(hashes.indexOf(options.algorithm) === -1){
    throw new Error('Algorithm "' + options.algorithm + '"  not supported. ' +
      'supported values: ' + hashes.join(', '));
  }

  if(encodings.indexOf(options.encoding) === -1){
    throw new Error('Encoding "' + options.encoding + '"  not supported. ' +
      'supported values: ' + encodings.join(', '));
  }
}
Beispiel #11
0
// Internals
function applyDefaults(object, options){
  var hashes = crypto.getHashes ? crypto.getHashes() : ['sha1', 'md5'];
  var encodings = ['buffer', 'hex', 'binary', 'base64'];
  
  options = options || {};
  options.algorithm = options.algorithm || 'sha1';
  options.encoding = options.encoding || 'hex';
  options.excludeValues = options.excludeValues ? true : false;
  options.algorithm = options.algorithm.toLowerCase();
  options.encoding = options.encoding.toLowerCase();
  options.ignoreUnknown = options.ignoreUnknown !== true ? false : true; // default to false
  options.respectType = options.respectType === false ? false : true; // default to true
  options.respectFunctionNames = options.respectFunctionNames === false ? false : true;
  options.respectFunctionProperties = options.respectFunctionProperties === false ? false : true;
  options.unorderedArrays = options.unorderedArrays !== true ? false : true; // default to false
  options.unorderedSets = options.unorderedSets === false ? false : true; // default to false
  options.replacer = options.replacer || undefined;

  if(typeof object === 'undefined') {
    throw new Error('Object argument required.');
  }

  hashes.push('passthrough');
  // if there is a case-insensitive match in the hashes list, accept it
  // (i.e. SHA256 for sha256)
  for (var i = 0; i < hashes.length; ++i) {
    if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) {
      options.algorithm = hashes[i];
    }
  }
  
  if(hashes.indexOf(options.algorithm) === -1){
    throw new Error('Algorithm "' + options.algorithm + '"  not supported. ' +
      'supported values: ' + hashes.join(', '));
  }

  if(encodings.indexOf(options.encoding) === -1 &&
     options.algorithm !== 'passthrough'){
    throw new Error('Encoding "' + options.encoding + '"  not supported. ' +
      'supported values: ' + encodings.join(', '));
  }
  
  return options;
}
Beispiel #12
0
	it ('crypt#pdkdf2', function(done) {

		var pw = "abc";
		var hashes = crypto.getHashes();
		var salt = crypto.randomBytes(128).toString('base64');
		var cryptPw = "";
		//console.dir(salt);
		crypto.pbkdf2(pw, salt, 10000, 128, function(err, key) {
			cryptPw = key.toString('base64');

			crypto.pbkdf2(pw, salt, 10000, 128, function(err, key) {
				var newPw = key.toString('base64');
				expect(newPw).to.be(cryptPw);

				done();
			});
		});

	});
	writePasswordHashes.calculateHashes = password => {

		const hashes = [ ]

		hashes.push({
			hash: {
				password,
				value:  password,
				digest: '',
				hash:   ''
			},
			hashDigestIndex,
			passwordIndex
		})

		++hashDigestIndex

		crypto.getHashes( ).forEach(hash => {
			constants.availableDigests.forEach(digest => {

				hashes.push({
					hash: {
						password,
						value: crypto.createHash(hash).update(password).digest(digest),
						digest,
						hash
					},
					hashDigestIndex,
					passwordIndex
				})

				++hashDigestIndex

			})

		})

		++passwordIndex

		return hashes

	}
Beispiel #14
0
module.exports.passwordCrypto = function(orginPassword){
    const suppotHashes = crypto.getHashes();
    if(!suppotHashes || suppotHashes.length < 1){
      throw new Error('该平台无支持加密的hash算法');
    }
    //使用的加密算法,首选sha256,没有则MD5,再没有则getHashed()返回的第一个
    var algorithm = null;
    if(suppotHashes.indexOf('md5') !== -1){
      algorithm = 'md5';
    }
    if(suppotHashes.indexOf('sha256') !== -1){
      algorithm = 'sha256';
    }
    if(!algorithm){
      algorithm = suppotHashes[0];
    }

    var shasum = crypto.createHash(algorithm);
    shasum.update(orginPassword);
    return shasum.digest('hex');
};
Beispiel #15
0
Client.prototype.connect = function(cfg) {
  var self = this;

  if (this._sock && this._sock.writable) {
    this.once('close', function() {
      self.connect(cfg);
    });
    this.end();
    return;
  }

  this.config.host = cfg.hostname || cfg.host || 'localhost';
  this.config.port = cfg.port || 22;
  this.config.forceIPv4 = cfg.forceIPv4 || false;
  this.config.forceIPv6 = cfg.forceIPv6 || false;
  this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number'
                                   && cfg.keepaliveCountMax >= 0
                                   ? cfg.keepaliveCountMax
                                   : 3);
  this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number'
                                   && cfg.keepaliveInterval > 0
                                   ? cfg.keepaliveInterval
                                   : 0);
  this.config.readyTimeout = (typeof cfg.readyTimeout === 'number'
                              && cfg.readyTimeout >= 0
                              ? cfg.readyTimeout
                              : 20000);
  this.config.compress = cfg.compress;

  this.config.username = cfg.username || cfg.user;
  this.config.password = (typeof cfg.password === 'string'
                          ? cfg.password
                          : undefined);
  this.config.privateKey = (typeof cfg.privateKey === 'string'
                            || Buffer.isBuffer(cfg.privateKey)
                            ? cfg.privateKey
                            : undefined);
  this.config.publicKey = undefined;
  this.config.localHostname = (typeof cfg.localHostname === 'string'
                               && cfg.localHostname.length
                               ? cfg.localHostname
                               : undefined);
  this.config.localUsername = (typeof cfg.localUsername === 'string'
                               && cfg.localUsername.length
                               ? cfg.localUsername
                               : undefined);
  this.config.tryKeyboard = (cfg.tryKeyboard === true);
  this.config.agent = (typeof cfg.agent === 'string' && cfg.agent.length
                       ? cfg.agent
                       : undefined);
  this.config.allowAgentFwd = (cfg.agentForward === true
                               && this.config.agent !== undefined);

  this.config.strictVendor = (typeof cfg.strictVendor === 'boolean'
                              ? cfg.strictVendor
                              : true);

  var debug = this.config.debug = (typeof cfg.debug === 'function'
                                   ? cfg.debug
                                   : DEBUG_NOOP);

  if (typeof this.config.username !== 'string')
    throw new Error('Invalid username');

  if (cfg.agentForward === true && !this.config.allowAgentFwd)
    throw new Error('You must set a valid agent path to allow agent forwarding');

  var callbacks = this._callbacks = [];
  this._channels = {};
  this._forwarding = {};
  this._acceptX11 = 0;
  this._agentFwdEnabled = false;
  this._curChan = -1;
  this._remoteVer = undefined;

  if (this.config.privateKey) {
    var privKeyInfo = parseKey(this.config.privateKey);
    if (privKeyInfo instanceof Error)
      throw new Error('Cannot parse privateKey: ' + privKeyInfo.message);
    if (!privKeyInfo.private)
      throw new Error('privateKey value does not contain a (valid) private key');
    if (privKeyInfo.encryption) {
      if (typeof cfg.passphrase !== 'string')
        throw new Error('Encrypted private key detected, but no passphrase given');
      decryptKey(privKeyInfo, cfg.passphrase);
    }
    this.config.privateKey = privKeyInfo;
    this.config.publicKey = genPublicKey(privKeyInfo);
  }

  var stream = this._sshstream = new SSH2Stream({
        debug: (debug === DEBUG_NOOP ? undefined : debug)
      }),
      sock = this._sock = (cfg.sock || new Socket());

  // drain stderr if we are connection hopping using an exec stream
  if (this._sock.stderr)
    this._sock.stderr.resume();

  // keepalive-related
  var kainterval = this.config.keepaliveInterval,
      kacountmax = this.config.keepaliveCountMax,
      kacount = 0,
      katimer;
  function sendKA() {
    if (++kacount > kacountmax) {
      clearInterval(katimer);
      if (sock.readable) {
        var err = new Error('Keepalive timeout');
        err.level = 'client-timeout';
        self.emit('error', err);
        sock.destroy();
      }
      return;
    }
    if (sock.writable) {
      // append dummy callback to keep correct callback order
      callbacks.push(resetKA);
      stream.ping();
    } else
      clearInterval(katimer);
  }
  function resetKA() {
    if (kainterval > 0) {
      kacount = 0;
      clearInterval(katimer);
      if (sock.writable)
        katimer = setInterval(sendKA, kainterval);
    }
  }
  this._resetKA = resetKA;

  stream.on('USERAUTH_BANNER', function(msg) {
    self.emit('banner', msg);
  });

  sock.on('connect', function() {
    debug('DEBUG: Client: Connected');
    self.emit('connect');
    self._sock.setKeepAlive(true);
    if (!cfg.sock)
      stream.pipe(sock).pipe(stream);
  }).on('timeout', function() {
    self.emit('timeout');
  }).on('error', function(err) {
    clearTimeout(self._readyTimeout);
    err.level = 'client-socket';
    self.emit('error', err);
  }).on('end', function() {
    stream.unpipe(sock);
    clearTimeout(self._readyTimeout);
    clearInterval(katimer);
    self.emit('end');
  }).on('close', function() {
    stream.unpipe(sock);
    clearTimeout(self._readyTimeout);
    clearInterval(katimer);
    self.emit('close');

    // notify outstanding channel requests of disconnection ...
    var callbacks_ = callbacks,
        err = new Error('No response from server');
    callbacks = self._callbacks = [];
    for (var i = 0; i < callbacks_.length; ++i)
      callbacks_[i](err);

    // simulate error for any channels waiting to be opened. this is safe
    // against successfully opened channels because the success and failure
    // event handlers are automatically removed when a success/failure response
    // is received
    var chanNos = Object.keys(self._channels);
    self._channels = {};
    for (var i = 0; i < chanNos.length; ++i) {
      stream.emit('CHANNEL_OPEN_FAILURE:' + chanNos[i], err);
      // emitting CHANNEL_CLOSE should be safe too and should help for any
      // special channels which might otherwise keep the process alive, such
      // as agent forwarding channels which have open unix sockets ...
      stream.emit('CHANNEL_CLOSE:' + chanNos[i]);
    }
  });
  stream.on('drain', function() {
    self.emit('drain');
  }).once('header', function(header) {
    self._remoteVer = header.versions.software;
  }).on('continue', function() {
    self.emit('continue');
  }).on('error', function(err) {
    err.level = 'protocol';
    self.emit('error', err);
  });

  if (typeof cfg.hostVerifier === 'function'
      && ~crypto.getHashes().indexOf(cfg.hostHash)) {
    var hashCb = cfg.hostVerifier,
        hasher = crypto.createHash(cfg.hostHash);
    stream.once('fingerprint', function(key, verify) {
      hasher.update(key, 'binary');
      verify(hashCb(hasher.digest('hex')));
    });
  }

  // begin authentication handling =============================================
  var auths = [],
      curAuth,
      agentKeys,
      agentKeyPos = 0;
  if (this.config.password !== undefined)
    auths.push('password');
  if (this.config.publicKey !== undefined)
    auths.push('publickey');
  if (this.config.agent !== undefined)
    auths.push('agent');
  if (this.config.tryKeyboard)
    auths.push('keyboard-interactive');
  if (this.config.publicKey !== undefined
      && this.config.localHostname !== undefined
      && this.config.localUsername !== undefined)
    auths.push('hostbased');
  auths.push('none');
  function tryNextAuth() {
    // TODO: better shutdown
    if (!auths.length) {
      stream.removeListener('USERAUTH_FAILURE', onUSERAUTH_FAILURE);
      stream.removeListener('USERAUTH_PK_OK', onUSERAUTH_PK_OK);
      var err = new Error('All configured authentication methods failed');
      err.level = 'client-authentication';
      self.emit('error', err);
      if (stream.writable)
        self.end();
      return;
    }

    curAuth = auths.shift();
    switch (curAuth) {
      case 'password':
        stream.authPassword(self.config.username, self.config.password);
      break;
      case 'publickey':
        stream.authPK(self.config.username, self.config.publicKey);
        stream.once('USERAUTH_PK_OK', onUSERAUTH_PK_OK);
      break;
      case 'hostbased':
        function hostbasedCb(buf, cb) {
          var signature = crypto.createSign(self.config.privateKey.type === 'rsa'
                                            ? 'RSA-SHA1'
                                            : 'DSA-SHA1');
          signature.update(buf);
          signature = signature.sign(self.config.privateKey.privateOrig, 'binary');
          signature = new Buffer(signature, 'binary');

          if (self.config.privateKey.type === 'dss' && signature.length > 40) {
            // this is a quick and dirty way to get from DER encoded r and s that
            // OpenSSL gives us, to just the bare values back to back (40 bytes
            // total) like OpenSSH (and possibly others) are expecting
            var newsig = new Buffer(40),
                rlen = signature[3],
                rstart = 4,
                sstart = 4 + 1 + rlen + 1;
            while (signature[rstart] === 0)
              ++rstart;
            while (signature[sstart] === 0)
              ++sstart;
            signature.copy(newsig, 0, rstart, rstart + 20);
            signature.copy(newsig, 20, sstart, sstart + 20);
            signature = newsig;
          }
          cb(signature);
        }
        stream.authHostbased(self.config.username,
                             self.config.publicKey,
                             self.config.localHostname,
                             self.config.localUsername,
                             hostbasedCb);
      break;
      case 'agent':
        agentQuery(self.config.agent, function(err, keys) {
          if (err) {
            err.level = 'agent';
            self.emit('error', err);
            agentKeys = undefined;
            return tryNextAuth();
          } else if (keys.length === 0) {
            debug('DEBUG: Agent: No keys stored in agent');
            agentKeys = undefined;
            return tryNextAuth();
          }

          agentKeys = keys;
          agentKeyPos = 0;

          stream.authPK(self.config.username, keys[0]);
          stream.once('USERAUTH_PK_OK', onUSERAUTH_PK_OK);
        });
      break;
      case 'keyboard-interactive':
        stream.authKeyboard(self.config.username);
        stream.on('USERAUTH_INFO_REQUEST', onUSERAUTH_INFO_REQUEST);
      break;
      case 'none':
        stream.authNone(self.config.username);
      break;
    }
  }
  function onUSERAUTH_INFO_REQUEST(name, instructions, lang, prompts) {
    var nprompts = (Array.isArray(prompts) ? prompts.length : 0);
    if (nprompts === 0) {
      debug('DEBUG: Client: Sending automatic USERAUTH_INFO_RESPONSE');
      return stream.authInfoRes();
    }
    // we sent a keyboard-interactive user authentication request and now the
    // server is sending us the prompts we need to present to the user
    self.emit('keyboard-interactive',
              name,
              instructions,
              lang,
              prompts,
              function(answers) {
                stream.authInfoRes(answers);
              });
  }
  function onUSERAUTH_PK_OK(keyAlgo, key) {
    if (curAuth === 'agent') {
      var agentKey = agentKeys[agentKeyPos],
          pubKeyFullType = agentKey.toString('ascii',
                                             4,
                                             4 + agentKey.readUInt32BE(0, true)),
          pubKeyType = pubKeyFullType.substring(4, 7);
      stream.authPK(self.config.username, 
                    agentKey,
                    function(buf, cb) {
        agentQuery(self.config.agent,
                   agentKey,
                   pubKeyType,
                   buf,
                   function(err, signed) {
          if (err) {
            err.level = 'agent';
            self.emit('error', err);
            agentKeys = undefined;
            return tryNextAuth();
          }

          var signature;

          if (signed.toString('ascii', 4, 11) === 'ssh-' + pubKeyType) {
            // skip algoLen + algo + sigLen
            signature = signed.slice(4 + 7 + 4);
          } else
            signature = signed;

          cb(signature);
        });
      });
    } else if (curAuth === 'publickey') {
      stream.authPK(self.config.username,
                    self.config.publicKey,
                    function(buf, cb) {
        var signature = crypto.createSign(self.config.privateKey.type === 'rsa'
                                          ? 'RSA-SHA1'
                                          : 'DSA-SHA1');
        signature.update(buf);
        signature = signature.sign(self.config.privateKey.privateOrig, 'binary');
        signature = new Buffer(signature, 'binary');

        if (self.config.privateKey.type === 'dss' && signature.length > 40) {
          // this is a quick and dirty way to get from DER encoded r and s that
          // OpenSSL gives us, to just the bare values back to back (40 bytes
          // total) like OpenSSH (and possibly others) are expecting
          var newsig = new Buffer(40),
              rlen = signature[3],
              rstart = 4,
              sstart = 4 + 1 + rlen + 1;
          while (signature[rstart] === 0)
            ++rstart;
          while (signature[sstart] === 0)
            ++sstart;
          signature.copy(newsig, 0, rstart, rstart + 20);
          signature.copy(newsig, 20, sstart, sstart + 20);
          signature = newsig;
        }
        cb(signature);
      });
    }
  }
  function onUSERAUTH_FAILURE(authsLeft, partial) {
    stream.removeListener('USERAUTH_PK_OK', onUSERAUTH_PK_OK);
    stream.removeListener('USERAUTH_INFO_REQUEST', onUSERAUTH_INFO_REQUEST);
    if (curAuth === 'agent') {
      debug('DEBUG: Client: Agent key #' + (agentKeyPos + 1) + ' failed');
      if (++agentKeyPos >= agentKeys.length) {
        debug('DEBUG: Agent: No more keys left to try');
        debug('DEBUG: Client: ' + curAuth + ' auth failed');
        agentKeys = undefined;
        tryNextAuth();
      } else {
        debug('DEBUG: Agent: Trying key #' + (agentKeyPos + 1));
        stream.authPK(self.config.username, agentKeys[agentKeyPos]);
        stream.once('USERAUTH_PK_OK', onUSERAUTH_PK_OK);
      }
      return;
    } else
      debug('DEBUG: Client: ' + curAuth + ' auth failed');

    tryNextAuth();
  }
  stream.once('USERAUTH_SUCCESS', function() {
    auths = undefined;
    stream.removeListener('USERAUTH_FAILURE', onUSERAUTH_FAILURE);
    stream.removeListener('USERAUTH_INFO_REQUEST', onUSERAUTH_INFO_REQUEST);
    /*if (self.config.agent && self._agentKeys)
      self._agentKeys = undefined;*/

    // start keepalive mechanism
    resetKA();

    clearTimeout(self._readyTimeout);

    self.emit('ready');
  }).on('USERAUTH_FAILURE', onUSERAUTH_FAILURE);
  // end authentication handling ===============================================

  // handle initial handshake completion
  stream.once('NEWKEYS', function() {
    stream.service('ssh-userauth');
    stream.once('SERVICE_ACCEPT', function(svcName) {
      if (svcName === 'ssh-userauth')
        tryNextAuth();
    });
  });

  // handle incoming requests from server, typically a forwarded TCP or X11
  // connection
  stream.on('CHANNEL_OPEN', function(info) {
    onCHANNEL_OPEN(self, info);
  });

  // handle responses for tcpip-forward and other global requests
  stream.on('REQUEST_SUCCESS', function(data) {
    if (callbacks.length)
      callbacks.shift()(false, data);
  }).on('REQUEST_FAILURE', function() {
    if (callbacks.length)
      callbacks.shift()(true);
  });

  stream.on('GLOBAL_REQUEST', function(name, wantReply, data) {
    // auto-reject all global requests, this can be especially useful if the
    // server is sending us dummy keepalive global requests
    if (wantReply)
      stream.requestFailure();
  });

  if (!cfg.sock) {
    var host = this.config.host,
        forceIPv4 = this.config.forceIPv4,
        forceIPv6 = this.config.forceIPv6;

    debug('DEBUG: Client: Trying '
          + host
          + ' on port '
          + this.config.port
          + ' ...');

    function doConnect() {
      startTimeout();
      self._sock.connect(self.config.port, host);
      self._sock.setNoDelay(true);
      self._sock.setMaxListeners(0);
      self._sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0);
    }

    if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6))
      doConnect();
    else {
      dnsLookup(host, (forceIPv4 ? 4 : 6), function(err, address, family) {
        if (err) {
          var error = new Error('Error while looking up '
                                + (forceIPv4 ? 'IPv4' : 'IPv6')
                                + ' address for host '
                                + host
                                + ': ' + err);
          clearTimeout(self._readyTimeout);
          error.level = 'client-dns';
          self.emit('error', error);
          self.emit('close');
          return;
        }
        host = address;
        doConnect();
      });
    }
  } else {
    startTimeout();
    stream.pipe(sock).pipe(stream);
  }

  function startTimeout() {
    if (self.config.readyTimeout > 0) {
      self._readyTimeout = setTimeout(function() {
        var err = new Error('Timed out while waiting for handshake');
        err.level = 'client-timeout';
        self.emit('error', err);
        sock.destroy();
      }, self.config.readyTimeout);
    }
  }
};
Beispiel #16
0
 it('should provide a list of available hashes', function() {
   var hashes = crypto.getHashes();
   expect( hashes.length ).toBeGreaterThan( 5 );
   expect( hashes ).toContain( 'md5' );
   expect( hashes ).toContain( 'sha1' );
 });
Beispiel #17
0
// Assume that we have at least AES-128-CBC.
const cryptoCiphers = crypto.getCiphers();
assert(crypto.getCiphers().includes('aes-128-cbc'));
validateList(cryptoCiphers);

// Assume that we have at least AES256-SHA.
const tlsCiphers = tls.getCiphers();
assert(tls.getCiphers().includes('aes256-sha'));
// There should be no capital letters in any element.
const noCapitals = /^[^A-Z]+$/;
assert(tlsCiphers.every((value) => noCapitals.test(value)));
validateList(tlsCiphers);

// Assert that we have sha and sha1 but not SHA and SHA1.
assert.notStrictEqual(0, crypto.getHashes().length);
assert(crypto.getHashes().includes('sha1'));
assert(crypto.getHashes().includes('sha'));
assert(!crypto.getHashes().includes('SHA1'));
assert(!crypto.getHashes().includes('SHA'));
assert(crypto.getHashes().includes('RSA-SHA1'));
assert(!crypto.getHashes().includes('rsa-sha1'));
validateList(crypto.getHashes());

// Assume that we have at least secp384r1.
assert.notStrictEqual(0, crypto.getCurves().length);
assert(crypto.getCurves().includes('secp384r1'));
assert(!crypto.getCurves().includes('SECP384R1'));
validateList(crypto.getCurves());

// Modifying return value from get* functions should not mutate subsequent
Beispiel #18
0
#!/usr/bin/env node

// node.js recipes
// analyzing types of data

var crypto = require('crypto'),
	hashes = crypto.getHashes();

hashes.forEach(function(hash) {
	['The quick brown fox jumps over the lazy dog.'].forEach(function(txt)  {
	var hashed;
	try {
		hashed = crypto.createHash(hash).update(txt).digest('hex');
	} catch (ex) {
		if (ex.message === 'Digest method not supported') {
			// not supported for this algo
			//console.log('not supported');
		} else {
			console.log(ex, hash);
		}
	}

	//console.log('\"' + hash + '\",\"' + hashed + '\"');
	console.log(hash + '\t' + hashed);
	});
});
	
Beispiel #19
0
HashBot.verifyAlgorithm = function(algo) {
  return _.contains(crypto.getHashes(), algo);
};
Beispiel #20
0
           'saltSALTsaltSALTsaltSALTsaltSALTsalt',
           4096,
           25,
           '\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8\xd8\x36\x62' +
           '\xc0\xe4\x4a\x8b\x29\x1a\x96\x4c\xf2\xf0\x70\x38');

testPBKDF2('pass\0word', 'sa\0lt', 4096, 16,
           '\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37\xd7\xf0\x34' +
           '\x25\xe0\xc3');

function assertSorted(list) {
  for (var i = 0, k = list.length - 1; i < k; ++i) {
    var a = list[i + 0];
    var b = list[i + 1];
    assert(a <= b);
  }
}

// Assume that we have at least AES256-SHA.
assert.notEqual(0, crypto.getCiphers());
assert.notEqual(-1, crypto.getCiphers().indexOf('AES256-SHA'));
assertSorted(crypto.getCiphers());

// Assert that we have sha and sha1 but not SHA and SHA1.
assert.notEqual(0, crypto.getHashes());
assert.notEqual(-1, crypto.getHashes().indexOf('sha1'));
assert.notEqual(-1, crypto.getHashes().indexOf('sha'));
assert.equal(-1, crypto.getHashes().indexOf('SHA1'));
assert.equal(-1, crypto.getHashes().indexOf('SHA'));
assertSorted(crypto.getHashes());
Beispiel #21
0
var crypto = require('crypto');
var fs = require("fs");

function hmacAlg(name, key) {
  var hash = crypto.createHmac(name, key);
  var txt = fs.ReadStream("pub.key");
  txt.on("data", function (data) {
    hash.update(data);
  })
  txt.on("end", function () {
    console.log(name + ":");
    console.log("\tkey:" + new Buffer(key).toString('hex'))
    console.log("\thash:" + hash.digest('hex'));
  })
}
for (var alg in crypto.getHashes()) hmacAlg(crypto.getHashes()[alg], crypto.randomBytes(64));
Beispiel #22
0
    return deferred.promise;
};

var cipherFound = false, hashFound = false;

// Test for required hash and cipher
crypto.getCiphers().forEach(function (val) {
    if (val === "aes-256-cbc") {
        cipherFound = true;
    }
});
if (!cipherFound) {
    console.log("Could not find support for 'aes-256-cbc' cipher!");
    process.exit(1);
}
crypto.getHashes().forEach(function (val) {
    if (val === "sha1") {
        hashFound = true;
    }
});
if (!hashFound) {
    console.log("Could not find support for 'sha1' hash!");
    process.exit(1);
}

http.createServer(function(req, res) {

    var sendResponse = function(resp) {
        var respJSON = JSON.stringify(resp);
        addCORSHeaders(res, respJSON.length);
        res.write(respJSON);
Beispiel #23
0
/*
 openssl encryption description
 - https://www.openssl.org/docs/apps/enc.html
 */


/**
 *
 * @return []
 */
function getSupportedHashes() {
    return crypto.getHashes();
}
Beispiel #24
0
// 打印支持的hash算法
// console.log(crypto.getHashes());

function hashAlgorithm(algorithm){
	var s1 = new Date();

	var filename = "package.json";
	var txt = fs.ReadStream(filename);

	var shasum = crypto.createHash(algorithm);
	txt.on('data', function(d) {
		shasum.update(d);
	});

	txt.on('end', function() {
		var d = shasum.digest('hex');
		var s2 = new Date();

		console.log(algorithm + ',' + (s2 - s1) + 'ms,' + d);
	});
}

function doHash(hashs){
	hashs.forEach(function(name){
		hashAlgorithm(name);
	})
}

var algs = crypto.getHashes();
doHash(algs);
Beispiel #25
0
		getHashers: function() {
			return crypto.getHashes();
		}
Beispiel #26
0
const crypto = require('crypto');
const tls = require('tls');
console.log(crypto.getHashes().join(' '));
console.log(crypto.getCiphers().join(' '));
console.log(tls.getCiphers().join(' '));
Beispiel #27
0
'use strict';

var crypto = require("crypto");
var algorithms = exports.algorithms = {};
algorithms.ciphers = crypto.getCiphers();
algorithms.hashes = crypto.getHashes();
algorithms.buffers = ['base64'];

/**
 * Cipher encoding/decoding using key
 *
 * @param str
 * @param key
 *
 * usage:
 *   Enc.aes192.encode('test', 'test)
 *   => 79caa93da9153f23fe10c7ddf2d8267e
 *
 *   Enc.aes192.decode('79caa93da9153f23fe10c7ddf2d8267e', 'test')
 *   => test
 *
 * Popular algorithms: 'aes192', 'blowfish', 'cast', 'des', 'des3', 'desx', 'rc2', 'rc4'
 * Use method name with _ eg: Enc.aes_128_cbc.encode(str, key)
 *
 */
algorithms.ciphers.forEach(function(alg){
    exports[alg.toLowerCase().replace(/\-/g, '_')] = {
        encode:function(str, key){
            var cipher = crypto.createCipher(alg, key),
                msg = [];
Beispiel #28
0
      .toString('hex');
  assert.strictEqual(modp2Secret, exmodp2Secret);
  assert.strictEqual(exmodp2.verifyError, DH_NOT_SUITABLE_GENERATOR);
}


const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' +
          '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' +
          '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' +
          'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF';
const bad_dh = crypto.createDiffieHellman(p, 'hex');
assert.strictEqual(bad_dh.verifyError, DH_NOT_SUITABLE_GENERATOR);


const availableCurves = new Set(crypto.getCurves());
const availableHashes = new Set(crypto.getHashes());

// Oakley curves do not clean up ERR stack, it was causing unexpected failure
// when accessing other OpenSSL APIs afterwards.
if (availableCurves.has('Oakley-EC2N-3')) {
  crypto.createECDH('Oakley-EC2N-3');
  crypto.createHash('sha256');
}

// Test ECDH
if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) {
  const ecdh1 = crypto.createECDH('prime256v1');
  const ecdh2 = crypto.createECDH('prime256v1');
  key1 = ecdh1.generateKeys();
  key2 = ecdh2.generateKeys('hex');
  secret1 = ecdh1.computeSecret(key2, 'hex', 'base64');
Beispiel #29
0
 format: function(val) {
   if (getHashes().indexOf(val) === -1) {
     throw new Error("Given hmac algorithm is not supported");
   }
 },
Beispiel #30
0
var crypto = require('crypto');
console.log(crypto.getHashes());

/*Crypto库是随Nodejs内核一起打包发布的,主要提供了加密、解密、签名、验证等功能。Crypto利用OpenSSL库来实现它的加密技术,
它提供OpenSSL中的一系列哈希方法,包括hmac、cipher、decipher、签名和验证等方法的封装。
详细见http://blog.fens.me/nodejs-crypto/
*/
 /*所有支持哈希算法的加密算法
 [ 'DSA',
 'DSA-SHA',
 'DSA-SHA1',
 'DSA-SHA1-old',
 'RSA-MD4',
 'RSA-MD5',
 'RSA-MDC2',
 'RSA-RIPEMD160',
 'RSA-SHA',
 'RSA-SHA1',
 'RSA-SHA1-2',
 'RSA-SHA224',
 'RSA-SHA256',
 'RSA-SHA384',
 'RSA-SHA512',
 'dsaEncryption',
 'dsaWithSHA',
 'dsaWithSHA1',
 'dss1',
 'ecdsa-with-SHA1',
 'md4',
 'md4WithRSAEncryption',
 'md5',