create callback to handle client signature (for client-certs)
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();
  }
654451
async def certify(client: Client, certification_signed_raw: str) -> ClientResponse:
    
    return await client.post(MODULE + '/certify', {'cert': certification_signed_raw}, rtype=RESPONSE_AIOHTTP)
513425
def call_signature(request_method)
      desc = rpc_desc(request_method)
      desc&.name ? desc.name.to_s.underscore.to_sym : nil
    end
525044
def _make_signing_request(self, message):
        """"""
        message = _helpers.to_bytes(message)

        method = 'POST'
        url = _SIGN_BLOB_URI.format(self._service_account_email)
        headers = {}
        body = json.dumps({
            'bytesToSign': base64.b64encode(message).decode('utf-8'),
        })

        self._credentials.before_request(self._request, method, url, headers)
        response = self._request(
            url=url, method=method, body=body, headers=headers)

        if response.status != http_client.OK:
            raise exceptions.TransportError(
                'Error calling the IAM signBytes API: {}'.format(
                    response.data))

        return json.loads(response.data.decode('utf-8'))
1161016
function verify(token, sign, options) {
  return (done) => {
    jwt.verifySync(token, sign, options, done);
  };
}
108217
def sign(self):
        """"""
        self.verify_integrity()
        
        if session.get('u2f_sign_required', False):
            if request.method == 'GET':
                response = self.get_signature_challenge()

                if response['status'] == 'ok':
                    return jsonify(response), 200
                else:
                    return jsonify(response), 404

            elif request.method == 'POST':
                response = self.verify_signature(request.json)

                if response['status'] == 'ok':
                    return jsonify(response), 201
                else:
                    return jsonify(response), 400

        return jsonify({'status': 'failed', 'error': 'Unauthorized!'}), 401
467636
def _validate_signature(minion_id, signature, impersonated_by_master):
    '''
    
    '''
    pki_dir = __opts__['pki_dir']
    if impersonated_by_master:
        public_key = '{0}/master.pub'.format(pki_dir)
    else:
        public_key = '{0}/minions/{1}'.format(pki_dir, minion_id)

    log.trace('Validating signature for %s', minion_id)
    signature = base64.b64decode(signature)
    if not salt.crypt.verify_signature(public_key, minion_id, signature):
        raise salt.exceptions.AuthenticationError(
            'Could not validate token request from {0}'.format(minion_id)
            )
    log.trace('Signature ok')
1301534
function (cert, cb) {
    var infoObject = {},
        subjectElements = [],
        err;

  	var openssl = spawn('openssl', ['req', '-noout', '-subject', '-nameopt', 'RFC2253']);

    // Catch stderr
    openssl.stderr.on('data', function (out) {
      err = new Error(out);

      // Callback and return array
  		return cb(err, infoObject);
    });

    openssl.stdout.on('data', function (out) {
      var data = out.toString();

      // Put each line into an array
      var lineArray = data.split('\n');

      // Filter out empty ones
      lineArray = lineArray.filter(function(n){ return n !== undefined && n !== '' });

      /* Construct infoObject */

      // Certificate
      infoObject.certificate = cert;

      // Subject
      infoObject.subject = {};
      // Split by "/" prefix
      subjectElements = lineArray[0].replace('subject=', '').split(',');
      // For each elements
      for (var iS = 0; iS < subjectElements.length; iS++) {
        // Split keys and values by "=" separator
        var subjectKeyValue = subjectElements[iS].split('=');
        infoObject.subject[subjectKeyValue[0]] = subjectKeyValue[1];
      }

      // Callback and return array
  		return cb(err, infoObject);
  	});

  	openssl.stdin.write(cert);
  	openssl.stdin.end();
  }
800002
public CallbackRequest handle(String signature, String payload)
            throws LineBotCallbackException, IOException {
        // validate signature
        if (signature == null || signature.length() == 0) {
            throw new LineBotCallbackException("Missing 'X-Line-Signature' header");
        }

        log.debug("got: {}", payload);

        final byte[] json = payload.getBytes(StandardCharsets.UTF_8);

        if (!lineSignatureValidator.validateSignature(json, signature)) {
            throw new LineBotCallbackException("Invalid API signature");
        }

        final CallbackRequest callbackRequest = objectMapper.readValue(json, CallbackRequest.class);
        if (callbackRequest == null || callbackRequest.getEvents() == null) {
            throw new LineBotCallbackException("Invalid content");
        }
        return callbackRequest;
    }
1049828
function doVerifyStep() {
    function verified(err, client, info) {
      if (err) { return self.error(err); }
      if (!client) { return self.fail(); }
      self.success(client, info);
    }
    
    // At this point, the assertion has been verified and authentication can
    // proceed.  Call the verify callback so the application can find and verify
    // the client instance.  Typically, the subject and issuer of the assertion
    // are the same, as the client is authenticating as itself.
    try {
      if (self._passReqToCallback) {
        var arity = self._key.length;
        if (arity == 4) {
          // This variation allows the application to detect the case in which
          // the issuer and subject of the assertion are different, and permit
          // or deny as necessary.
          self._verify(req, payload.iss || header.iss, header, verified);
        } else { // arity == 3
          self._verify(req, payload.iss || header.iss, keyed);
        }
      } else {
        var arity = self._key.length;
        if (arity == 3) {
          // This variation allows the application to detect the case in which
          // the issuer and subject of the assertion are different, and permit
          // or deny as necessary.
          self._verify(payload.sub || payload.iss, payload.iss, verified);
        } else { // arity == 2
          self._verify(payload.sub || payload.iss, verified);
        }
      }
    } catch (ex) {
      return self.error(ex);
    }
  }
1178227
def apply_signature(cls, instance, async=True, countdown=None, is_heavy_task=False, **kwargs):
        
        serialized_instance = utils.serialize_instance(instance)

        signature = cls.get_task_signature(instance, serialized_instance, **kwargs)
        link = cls.get_success_signature(instance, serialized_instance, **kwargs)
        link_error = cls.get_failure_signature(instance, serialized_instance, **kwargs)

        if async:
            return signature.apply_async(link=link, link_error=link_error, countdown=countdown,
                                         queue=is_heavy_task and 'heavy' or None)
        else:
            result = signature.apply()
            callback = link if not result.failed() else link_error
            if callback is not None:
                cls._apply_callback(callback, result)

        return result.get()
658263
def make_signature(signer_func, data_to_sign, public_algo,
                   hashed_subpackets, unhashed_subpackets, sig_type=0):
    """"""
    # pylint: disable=too-many-arguments
    header = struct.pack('>BBBB',
                         4,         # version
                         sig_type,  # rfc4880 (section-5.2.1)
                         public_algo,
                         8)         # hash_alg (SHA256)
    hashed = subpackets(*hashed_subpackets)
    unhashed = subpackets(*unhashed_subpackets)
    tail = b'\x04\xff' + struct.pack('>L', len(header) + len(hashed))
    data_to_hash = data_to_sign + header + hashed + tail

    log.debug('hashing %d bytes', len(data_to_hash))
    digest = hashlib.sha256(data_to_hash).digest()
    log.debug('signing digest: %s', util.hexlify(digest))
    params = signer_func(digest=digest)
    sig = b''.join(mpi(p) for p in params)

    return bytes(header + hashed + unhashed +
                 digest[:2] +  # used for decoder's sanity check
                 sig)
19765
def sign_request(method, uri, form_args)
      # Convert non-string keys to strings so the sort works
      args = {}
      if form_args
        form_args.each do |key, value|
          next unless value and value != ""

          key = key.to_s unless key.is_a?(String)
          args[key] = value
        end
      end

      # Add the necessary OAuth args
      args["oauth_version"] = "1.0"
      args["oauth_consumer_key"] = @config[:api_key]
      args["oauth_nonce"] = Digest::MD5.hexdigest("#{Time.now.to_f}#{rand(10 ** 30)}")
      args["oauth_signature_method"] = "HMAC-SHA1"
      args["oauth_timestamp"] = Time.now.utc.to_i
      args["oauth_token"] = @config[:user][:token]

      # RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) says:
      #
      #     Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
      #     reserved characters used for their reserved purposes may be used
      #     unencoded within a URL.
      #
      # However, if we don't escape apostrophes and parentheses the SmugMug API fails
      # with an invalid signature error:
      #
      #     Error #35, invalid signature (SmugMug::OAuthError)
      #
      # To overcome this, define a new unreserved character list and use this in URI::escape
      unreserved = "\\-_.!~*a-zA-Z\\d"
      unsafe = Regexp.new("[^#{unreserved}]", false, 'N')

      # Sort the params
      sorted_args = []
      args.sort.each do |key, value|
        sorted_args.push("#{key.to_s}=#{URI::escape(value.to_s, unsafe)}")
      end

      postdata = sorted_args.join("&")

      # Final string to hash
      sig_base = "#{method}&#{URI::escape("#{uri.scheme}://#{uri.host}#{uri.path}", unsafe)}&#{URI::escape(postdata, unsafe)}"

      signature = OpenSSL::HMAC.digest(@digest, "#{@config[:oauth_secret]}&#{@config[:user][:secret]}", sig_base)
      signature = URI::escape(Base64.encode64(signature).chomp, unsafe)

      if uri == API_URI
        "#{postdata}&oauth_signature=#{signature}"
      else
        args["oauth_signature"] = signature
        args
      end
    end
730704
function signAWSRequest({ credentials, request }) {
  const signer = new AWS.Signers.V4(request, 'es')
  signer.addAuthorization(credentials, new Date())
  return request
}
1192582
async def fetch_signatures(endpoint, protocol, idgen):
        """"""
        async with aiohttp.ClientSession() as session:
            req = {
                "method": "getMethodTypes",
                "params": [''],
                "version": "1.0",
                "id": next(idgen),
            }

            if protocol == ProtocolType.WebSocket:
                async with session.ws_connect(endpoint, timeout=2) as s:
                    await s.send_json(req)
                    res = await s.receive_json()
                    return res
            else:
                res = await session.post(endpoint, json=req)
                json = await res.json()

                return json
302029
function (req, callback) {
    var params = req.body
    var clientId = params.client_id
    var clientSecret = params.client_secret

    // missing credentials
    if (!clientId || !clientSecret) {
      return callback(new AuthorizationError({
        error: 'unauthorized_client',
        error_description: 'Missing client credentials',
        statusCode: 400
      }))
    }

    Client.get(clientId, function (err, client) {
      if (err) { return callback(err) }

      // Unknown client
      if (!client) {
        return callback(new AuthorizationError({
          error: 'unauthorized_client',
          error_description: 'Unknown client identifier',
          statusCode: 401
        }))
      }

      // Mismatching secret
      if (client.client_secret !== clientSecret) {
        return callback(new AuthorizationError({
          error: 'unauthorized_client',
          error_description: 'Mismatching client secret',
          statusCode: 401
        }))
      }

      callback(null, client)
    })
  }
661202
def _signature(self, cmd):
        '''
        
        '''
        result = {}

        client = cmd.get('client', 'minion')
        if client == 'minion':
            cmd['fun'] = 'sys.argspec'
            cmd['kwarg'] = dict(module=cmd['module'])
            result = self.run(cmd)
        elif client == 'master':
            parts = cmd['module'].split('.')
            client = parts[0]
            module = '.'.join(parts[1:])  # strip prefix
            if client == 'wheel':
                functions = self.wheelClient.functions
            elif client == 'runner':
                functions = self.runnerClient.functions
            result = {'master': salt.utils.args.argspec_report(functions, module)}
        return result