// Sign adds the JWT auth header.
975895
func (s *JWTSigner) Sign(req *http.Request) error {
	return signFromSource(s.TokenSource, req)
}
1073413
func (s *GenericSigner) Sign(data common.Hash) (signature Signature, err error) {
	signaturebytes, err := crypto.Sign(data.Bytes(), s.PrivKey)
	if err != nil {
		return
	}
	copy(signature[:], signaturebytes)
	return
}
231052
func Sign(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, options ...Option) ([]byte, error) {
	var hdrs Headers = &StandardHeaders{}
	for _, o := range options {
		switch o.Name() {
		case optkeyHeaders:
			hdrs = o.Value().(Headers)
		}
	}

	signer, err := sign.New(alg)
	if err != nil {
		return nil, errors.Wrap(err, `failed to create signer`)
	}

	hdrs.Set(AlgorithmKey, signer.Algorithm())

	hdrbuf, err := json.Marshal(hdrs)
	if err != nil {
		return nil, errors.Wrap(err, `failed to marshal headers`)
	}

	var buf bytes.Buffer
	enc := base64.NewEncoder(base64.RawURLEncoding, &buf)
	if _, err := enc.Write(hdrbuf); err != nil {
		return nil, errors.Wrap(err, `failed to write headers as base64`)
	}
	if err := enc.Close(); err != nil {
		return nil, errors.Wrap(err, `failed to finalize writing headers as base64`)
	}

	buf.WriteByte('.')
	enc = base64.NewEncoder(base64.RawURLEncoding, &buf)
	if _, err := enc.Write(payload); err != nil {
		return nil, errors.Wrap(err, `failed to write payload as base64`)
	}
	if err := enc.Close(); err != nil {
		return nil, errors.Wrap(err, `failed to finalize writing payload as base64`)
	}

	signature, err := signer.Sign(buf.Bytes(), key)
	if err != nil {
		return nil, errors.Wrap(err, `failed to sign payload`)
	}

	buf.WriteByte('.')
	enc = base64.NewEncoder(base64.RawURLEncoding, &buf)
	if _, err := enc.Write(signature); err != nil {
		return nil, errors.Wrap(err, `failed to write signature as base64`)
	}
	if err := enc.Close(); err != nil {
		return nil, errors.Wrap(err, `failed to finalize writing signature as base64`)
	}

	return buf.Bytes(), nil
}
1127300
func (s *ConnectCA) Sign(
	args *structs.CASignRequest,
	reply *structs.IssuedCert) error {
	// Exit early if Connect hasn't been enabled.
	if !s.srv.config.ConnectEnabled {
		return ErrConnectNotEnabled
	}

	if done, err := s.srv.forward("ConnectCA.Sign", args, args, reply); done {
		return err
	}

	// Parse the CSR
	csr, err := connect.ParseCSR(args.CSR)
	if err != nil {
		return err
	}

	// Parse the SPIFFE ID
	spiffeID, err := connect.ParseCertURI(csr.URIs[0])
	if err != nil {
		return err
	}
	serviceID, ok := spiffeID.(*connect.SpiffeIDService)
	if !ok {
		return fmt.Errorf("SPIFFE ID in CSR must be a service ID")
	}

	provider, caRoot := s.srv.getCAProvider()
	if provider == nil {
		return fmt.Errorf("internal error: CA provider is nil")
	}

	// Verify that the CSR entity is in the cluster's trust domain
	state := s.srv.fsm.State()
	_, config, err := state.CAConfig()
	if err != nil {
		return err
	}
	signingID := connect.SpiffeIDSigningForCluster(config)
	if !signingID.CanSign(serviceID) {
		return fmt.Errorf("SPIFFE ID in CSR from a different trust domain: %s, "+
			"we are %s", serviceID.Host, signingID.Host())
	}

	// Verify that the ACL token provided has permission to act as this service
	rule, err := s.srv.ResolveToken(args.Token)
	if err != nil {
		return err
	}
	if rule != nil && !rule.ServiceWrite(serviceID.Service, nil) {
		return acl.ErrPermissionDenied
	}

	// Verify that the DC in the service URI matches us. We might relax this
	// requirement later but being restrictive for now is safer.
	if serviceID.Datacenter != s.srv.config.Datacenter {
		return fmt.Errorf("SPIFFE ID in CSR from a different datacenter: %s, "+
			"we are %s", serviceID.Datacenter, s.srv.config.Datacenter)
	}

	commonCfg, err := config.GetCommonConfig()
	if err != nil {
		return err
	}
	if commonCfg.CSRMaxPerSecond > 0 {
		lim := s.getCSRRateLimiterWithLimit(rate.Limit(commonCfg.CSRMaxPerSecond))
		// Wait up to the small threshold we allow for a token.
		ctx, cancel := context.WithTimeout(context.Background(), csrLimitWait)
		defer cancel()
		if lim.Wait(ctx) != nil {
			return ErrRateLimited
		}
	} else if commonCfg.CSRMaxConcurrent > 0 {
		s.csrConcurrencyLimiter.SetSize(int64(commonCfg.CSRMaxConcurrent))
		ctx, cancel := context.WithTimeout(context.Background(), csrLimitWait)
		defer cancel()
		if err := s.csrConcurrencyLimiter.Acquire(ctx); err != nil {
			return ErrRateLimited
		}
		defer s.csrConcurrencyLimiter.Release()
	}

	// All seems to be in order, actually sign it.
	pem, err := provider.Sign(csr)
	if err != nil {
		return err
	}

	// Append any intermediates needed by this root.
	for _, p := range caRoot.IntermediateCerts {
		pem = strings.TrimSpace(pem) + "\n" + p
	}

	// Append our local CA's intermediate if there is one.
	inter, err := provider.ActiveIntermediate()
	if err != nil {
		return err
	}
	root, err := provider.ActiveRoot()
	if err != nil {
		return err
	}

	if inter != root {
		pem = strings.TrimSpace(pem) + "\n" + inter
	}

	// TODO(banks): when we implement IssuedCerts table we can use the insert to
	// that as the raft index to return in response.
	//
	// UPDATE(mkeeler): The original implementation relied on updating the CAConfig
	// and using its index as the ModifyIndex for certs. This was buggy. The long
	// term goal is still to insert some metadata into raft about the certificates
	// and use that raft index for the ModifyIndex. This is a partial step in that
	// direction except that we only are setting an index and not storing the
	// metadata.
	req := structs.CALeafRequest{
		Op:           structs.CALeafOpIncrementIndex,
		Datacenter:   s.srv.config.Datacenter,
		WriteRequest: structs.WriteRequest{Token: args.Token},
	}

	resp, err := s.srv.raftApply(structs.ConnectCALeafRequestType|structs.IgnoreUnknownTypeFlag, &req)
	if err != nil {
		return err
	}

	modIdx, ok := resp.(uint64)
	if !ok {
		return fmt.Errorf("Invalid response from updating the leaf cert index")
	}

	cert, err := connect.ParseCert(pem)
	if err != nil {
		return err
	}

	// Set the response
	*reply = structs.IssuedCert{
		SerialNumber: connect.HexString(cert.SerialNumber.Bytes()),
		CertPEM:      pem,
		Service:      serviceID.Service,
		ServiceURI:   cert.URIs[0].String(),
		ValidAfter:   cert.NotBefore,
		ValidBefore:  cert.NotAfter,
		RaftIndex: structs.RaftIndex{
			ModifyIndex: modIdx,
			CreateIndex: modIdx,
		},
	}

	return nil
}
220609
func (s *Signature) sign(key string, r *http.Request) error {
	sig, err := s.calculateSignature(key, r)
	if err != nil {
		return err
	}

	s.Signature = sig
	return nil
}
1252369
func (s *APIKeySigner) Sign(req *http.Request) error {
	if s.KeyName == "" {
		s.KeyName = "Authorization"
	}
	if s.Format == "" {
		s.Format = "Bearer %s"
	}
	name := s.KeyName
	format := s.Format
	val := fmt.Sprintf(format, s.KeyValue)
	if s.SignQuery && val != "" {
		query := req.URL.Query()
		query.Set(name, val)
		req.URL.RawQuery = query.Encode()
	} else {
		req.Header.Set(name, val)
	}
	return nil
}
152861
func (r *AttachmentHTTPSrv) Sign(payload []byte) ([]byte, error) {
	arg := chat1.S3SignArg{
		Payload: payload,
		Version: 1,
	}
	return r.ri().S3Sign(context.Background(), arg)
}
742655
func (k RSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
	hashed := sha256.Sum256(msg)
	if opts == nil {
		opts = &rsa.PSSOptions{
			SaltLength: rsa.PSSSaltLengthEqualsHash,
			Hash:       crypto.SHA256,
		}
	}
	return k.CryptoSigner().Sign(rand, hashed[:], opts)
}
770545
func Sign(version Version, plaintext []byte, signer SigningSecretKey) ([]byte, error) {
	buf, err := signToStream(version, plaintext, signer, NewSignStream)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
957196
func (s *BasicSigner) Sign(req *http.Request) error {
	if s.Username != "" && s.Password != "" {
		req.SetBasicAuth(s.Username, s.Password)
	}
	return nil
}
870338
func (m *SigningMethodRSAPSS) Sign(raw []byte, key interface{}) (Signature, error) {
	rsaKey, ok := key.(*rsa.PrivateKey)
	if !ok {
		return nil, ErrInvalidKey
	}
	sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, m.sum(raw), m.Options)
	if err != nil {
		return nil, err
	}
	return Signature(sigBytes), nil
}
621805
func (p *x509Signer) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
	signature, err := pkcs11helpers.Sign(p.ctx, p.session, p.objectHandle, p.keyType, digest, opts.HashFunc())
	if err != nil {
		return nil, err
	}

	if p.keyType == pkcs11helpers.ECDSAKey {
		// Convert from the PKCS#11 format to the RFC 5480 format so that
		// it can be used in a X.509 certificate
		r := big.NewInt(0).SetBytes(signature[:len(signature)/2])
		s := big.NewInt(0).SetBytes(signature[len(signature)/2:])
		signature, err = asn1.Marshal(struct {
			R, S *big.Int
		}{R: r, S: s})
		if err != nil {
			return nil, fmt.Errorf("failed to convert signature to RFC 5480 format: %s", err)
		}
	}
	return signature, nil
}
955837
func (hash *Hash) Sign(key *Key) ([]byte, error) {
	var dataLen C.UINT32
	var cData *C.BYTE
	err := tspiError(C.Tspi_Hash_Sign(hash.handle, key.handle, &dataLen, &cData))
	data := C.GoBytes(unsafe.Pointer(cData), (C.int)(dataLen))
	C.Tspi_Context_FreeMemory(hash.context, cData)

	if err != nil {
		return nil, err
	}

	return data, nil
}
879522
func (c *Client) Sign(req *http.Request) (err error) {
	if c.AppToken == nil {
		if err = c.FetchAppToken(); err != nil {
			return
		}
	}
	var (
		h = fmt.Sprintf("Bearer %v", c.AppToken.AccessToken)
	)
	req.Header.Set("Authorization", h)
	return
}
810982
func (c *Consumer) Sign(req *http.Request, token Token) error {
	return c.SignParams(req, token, nil)
}
679842
func (privKey PrivKeySecp256k1) Sign(msg []byte) ([]byte, error) {
	rsv, err := secp256k1.Sign(crypto.Sha256(msg), privKey[:])
	if err != nil {
		return nil, err
	}
	// we do not need v  in r||s||v:
	rs := rsv[:len(rsv)-1]
	return rs, nil
}
597976
func (s *Signer) Sign(r *http.Request) {
	t := time.Now().Unix()
	n := s.GenerateNonce(t, "x", "y")
	values := r.URL.Query()
	values.Add(s.nonceParam, n)
	values.Add(s.timestampParam, strconv.Itoa(int(t)))
	r.URL.RawQuery = values.Encode()
	signature := s.Signature(r)

	//add signature to request
	values.Add(s.signatureParam, signature)
	r.URL.RawQuery = values.Encode()
}