/* Utility function for signing connection
Will be used with function based authentication method
(self sufficient authentication - requires Secret Key)
544442
function signSubscription () {
    var to_sign = args.sid + ':' + args.channel + '.' + args.resource +
                  ':ttl=' + args.ttl + ':read=' + args.read +
                  ':write=' + args.write

    if (self.bbt.userinfo.userid) {
      to_sign = to_sign + ':userid=' + self.bbt.userinfo.userid
    }

    var signature = crypto.createHmac('sha1', self.bbt.transport.secretKey)
    .update(to_sign)
    .digest('base64')

    var auth = {
      auth: self.bbt.transport.key + ':' + signature
    }

    if (self.bbt.userinfo.userid) {
      auth.userid = self.bbt.userinfo.userid
    }

    return auth
  }
740271
function authenticateStragglers(self, connection, callback) {
      // Get any non authenticated connections
      var connections = self.nonAuthenticatedConnections.slice(0);
      var nonAuthenticatedConnections = self.nonAuthenticatedConnections;
      self.nonAuthenticatedConnections = [];

      // Establish if the connection need to be authenticated
      // Add to authentication list if
      // 1. we were in an authentication process when the operation was executed
      // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened
      if (
        connection.workItems.length === 1 &&
        (connection.workItems[0].authenticating === true ||
          (typeof connection.workItems[0].authenticatingTimestamp === 'number' &&
            connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp))
      ) {
        // Add connection to the list
        connections.push(connection);
      }

      // No connections need to be re-authenticated
      if (connections.length === 0) {
        // Release the connection back to the pool
        moveConnectionBetween(connection, self.inUseConnections, self.availableConnections);
        // Finish
        return callback();
      }

      // Apply re-authentication to all connections before releasing back to pool
      var connectionCount = connections.length;
      // Authenticate all connections
      for (var i = 0; i < connectionCount; i++) {
        reauthenticate(self, connections[i], function() {
          connectionCount = connectionCount - 1;

          if (connectionCount === 0) {
            // Put non authenticated connections in available connections
            self.availableConnections = self.availableConnections.concat(
              nonAuthenticatedConnections
            );
            // Release the connection back to the pool
            moveConnectionBetween(connection, self.inUseConnections, self.availableConnections);
            // Return
            callback();
          }
        });
      }
    }
455040
function verifySecondSignature (transaction, publicKey) {
	var bytes = getBytes(transaction);
	var data2 = Buffer.alloc(bytes.length - 64);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash('sha256').update(data2.toString('hex'), 'hex').digest();

	var signSignatureBuffer = Buffer.from(transaction.signSignature, 'hex');
	var publicKeyBuffer = Buffer.from(publicKey, 'hex');
	var res = naclInstance.crypto_sign_verify_detached(signSignatureBuffer, hash, publicKeyBuffer);

	return res;
}
79309
function readFullSigningPaths(conn, address, arrSigningDeviceAddresses, handleSigningPaths){
	
	var assocSigningPaths = {};
	
	function goDeeper(member_address, path_prefix, onDone){
		// first, look for wallet addresses
		var sql = "SELECT signing_path FROM my_addresses JOIN wallet_signing_paths USING(wallet) WHERE address=?";
		var arrParams = [member_address];
		if (arrSigningDeviceAddresses && arrSigningDeviceAddresses.length > 0){
			sql += " AND device_address IN(?)";
			arrParams.push(arrSigningDeviceAddresses);
		}
		conn.query(sql, arrParams, function(rows){
			rows.forEach(function(row){
				assocSigningPaths[path_prefix + row.signing_path.substr(1)] = 'key';
			});
			if (rows.length > 0)
				return onDone();
			// next, look for shared addresses, and search from there recursively
			sql = "SELECT signing_path, address FROM shared_address_signing_paths WHERE shared_address=?";
			arrParams = [member_address];
			if (arrSigningDeviceAddresses && arrSigningDeviceAddresses.length > 0){
				sql += " AND device_address IN(?)";
				arrParams.push(arrSigningDeviceAddresses);
			}
			conn.query(sql, arrParams, function(rows){
				if(rows.length > 0) {
					async.eachSeries(
						rows,
						function (row, cb) {
							if (row.address === '') { // merkle
								assocSigningPaths[path_prefix + row.signing_path.substr(1)] = 'merkle';
								return cb();
							}

							goDeeper(row.address, path_prefix + row.signing_path.substr(1), cb);
						},
						onDone
					);
				} else {
					assocSigningPaths[path_prefix] = 'key';
					onDone();
				}
			});
		});
	}
	
	goDeeper(address, 'r', function(){
		handleSigningPaths(assocSigningPaths); // order of signing paths is not significant
	});
}
535346
function(method, url, timestamp) {
        var data = [method, url, this.options.publicKey, timestamp].join('|'),
            signature = crypto.sha256(this.options.privateKey, data);

        return signature;
    }
638058
public void signIn(String key, Collection<WebSocketConnection> connections) {
        if (connections.isEmpty()) {
            return;
        }
        Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>();
        for (WebSocketConnection conn : connections) {
            newMap.put(conn, conn);
        }
        ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key);
        bag.putAll(newMap);
    }
662318
function getFunctionSignature(fn) {
  let str = fn.toString()

  // Strip comments.
  str = str.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, '')

  const match = str.match(/\(([^)]*)\)/)

  if (match) {
    let res = match[1]

    // Strip leading and trailing whitespace.
    res = res.replace(/^\s+|\s+$/g, '')

    let sig = res.split(/\s*,\s*/)

    if (sig.length === 1 && !sig[0]) {
      sig.length = 0
    }

    const signature = []

    for (let key of sig) {
      // TODO: Handle rest parameters. The position of the rest
      // parameter matters, so this requires some thought. The
      // following signatures are all different:
      // * function (...rest, foo, bar)
      // * function (foo, ...rest, bar)
      // * function (foo, bar, ...rest)
      // For now, just ignore rest parameters...
      if (key.indexOf('...') === 0) {
        continue
      }

      // If there is a default value defined, remove it from the
      // key.
      key = key.replace(/\s*=.*$/, '')

      // TODO: Should we do something with destructuring
      // assignments?

      signature.push(key)
    }

    return signature
  }
  else {
    return []
  }
}
219326
function getSignature ({
  params,
  accessKeySecret
}) {
  const paramString = paramsToString(params)
  const stringToSign = `POST&${encodeURIComponent('/')}&${encodeURIComponent(paramString)}`

  return crypto
    .createHmac('sha1', `${accessKeySecret}&`)
    .update(stringToSign)
    .digest('base64')
}
1063506
function( keys ) {
		var lookupString = keys.toString();
		var id = this.plainObjectSignatureLookup[lookupString];			
		if (id === undefined) {

			// Create new signature buffer
			var sigbuf = [];
			sigbuf.push( pack2b( keys.length, false ) );
			for (var i=0, l=keys.length; i<l; ++i) {
				sigbuf.push( pack2b( this.stringID(keys[i]), false ) );
			}

			// Keep on table
			this.plainObjectSignatureTable.push( Buffer.concat( sigbuf ) );
			this.plainObjectSignatureLookup[lookupString] 
				= id = this.plainObjectSignatureTable.length - 1;

		}
		return id;
	}
401162
private String createSignature(Credentials credentials, String secretKey) {
        return new SignatureGenerator().generate(
                secretKey,
                credentials.getMethod(),
                credentials.getTimestamp(),
                credentials.getPath(),
                credentials.getContent());
    }
697284
static void sign(SignableSAMLObject signableObj, Credential signingCredential, String signatureAlgorithm) {
        requireNonNull(signableObj, "signableObj");
        requireNonNull(signingCredential, "signingCredential");
        requireNonNull(signatureAlgorithm, "signatureAlgorithm");

        final Signature signature = signatureBuilder.buildObject();
        signature.setSignatureAlgorithm(signatureAlgorithm);
        signature.setSigningCredential(signingCredential);
        signature.setCanonicalizationAlgorithm(ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        try {
            signature.setKeyInfo(keyInfoGenerator.generate(signingCredential));
        } catch (SecurityException e) {
            throw new SamlException("failed to create a key info of signing credential", e);
        }

        signableObj.setSignature(signature);
        serialize(signableObj);

        try {
            Signer.signObject(signature);
        } catch (SignatureException e) {
            throw new SamlException("failed to sign a SAML object", e);
        }
    }
345032
def sign(self, consumer_secret, method, url, oauth_token_secret=None,
             **params):
        """"""
        # build the url the same way aiohttp will build the query later on
        # cf https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/client.py#L151
        # and https://github.com/KeepSafe/aiohttp/blob/master/aiohttp/client_reqrep.py#L81
        url = yarl.URL(url).with_query(sorted(params.items()))
        url, params = str(url).split('?', 1)
        method = method.upper()

        signature = b"&".join(map(self._escape, (method, url, params)))

        key = self._escape(consumer_secret) + b"&"
        if oauth_token_secret:
            key += self._escape(oauth_token_secret)

        hashed = hmac.new(key, signature, sha1)
        return base64.b64encode(hashed.digest()).decode()
556738
function(c, signature) {
    if(c.session.certificateRequest !== null &&
      c.session.clientCertificate !== null) {
      // create certificate verify message
      tls.queue(c, tls.createRecord(c, {
        type: tls.ContentType.handshake,
        data: tls.createCertificateVerify(c, signature)
      }));
    }

    // create change cipher spec message
    tls.queue(c, tls.createRecord(c, {
      type: tls.ContentType.change_cipher_spec,
      data: tls.createChangeCipherSpec()
    }));

    // create pending state
    c.state.pending = tls.createConnectionState(c);

    // change current write state to pending write state
    c.state.current.write = c.state.pending.write;

    // create finished message
    tls.queue(c, tls.createRecord(c, {
      type: tls.ContentType.handshake,
      data: tls.createFinished(c)
    }));

    // expect a server ChangeCipherSpec message next
    c.expect = SCC;

    // send records
    tls.flush(c);

    // continue
    c.process();
  }
1345207
@SneakyThrows
    private static SignatureTrustEngine buildSignatureTrustEngine(final WsFederationConfiguration wsFederationConfiguration) {
        val signingWallet = wsFederationConfiguration.getSigningWallet();
        LOGGER.debug("Building signature trust engine based on the following signing certificates:");
        signingWallet.forEach(c -> LOGGER.debug("Credential entity id [{}] with public key [{}]", c.getEntityId(), c.getPublicKey()));

        val resolver = new StaticCredentialResolver(signingWallet);
        val keyResolver = new StaticKeyInfoCredentialResolver(signingWallet);
        return new ExplicitKeySignatureTrustEngine(resolver, keyResolver);
    }
860788
def sign(key, qs):
    """"""
    sig = derive_signature(key, qs)
    return "%s&%s" % (qs, urlencode([("sig", sig)]))
582478
function preconnect(user, sshKeyPath, ipaddress, cb, pollCount) {
  if (pollCount === undefined) {
    pollCount = 0;
  }

  logger.info({
    user: user,
    identityFile: sshKeyPath,
    ipAddress: ipaddress
  }, 'waiting for connectivity');

  portscanner.checkPortStatus(22, ipaddress, function(err, status) {
    if (status === 'closed') {
      if (pollCount > MAX_POLLS) {
        pollCount = 0;
        cb('timeout exceeded - unable to connect to: ' + ipaddress);
      }
      else {
        pollCount = pollCount + 1;
        setTimeout(function() { preconnect(user, sshKeyPath, ipaddress, cb, pollCount); }, POLL_INTERVAL);
      }
    }
    else if (status === 'open') {
      pollCount = 0;
      sshCheck.check(ipaddress, user, sshKeyPath, null, function(err) {
        cb(err);
      });
    }
  });
}
256192
public byte[] sign(byte[] content,PrivateKey privateKey)  
    {  
        try   
        {  
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);  
            signature.initSign(privateKey);  
            signature.update(content);  
            return signature.sign();  
        }catch (Exception e)   
        {  
            log.error(e.getMessage(),e);
        }  
        return null;  
    }