// SignSDKRequest requests with signature version 2.
//
// Will sign the requests with the service config's Credentials object
// Signing is skipped if the credentials is the credentials.AnonymousCredentials
// object.
196042
func SignSDKRequest(req *request.Request) {
	// If the request does not need to be signed ignore the signing of the
	// request if the AnonymousCredentials object is used.
	if req.Config.Credentials == credentials.AnonymousCredentials {
		return
	}

	if req.HTTPRequest.Method != "POST" && req.HTTPRequest.Method != "GET" {
		// The V2 signer only supports GET and POST
		req.Error = errInvalidMethod
		return
	}

	v2 := signer{
		Request:     req.HTTPRequest,
		Time:        req.Time,
		Credentials: req.Config.Credentials,
		Debug:       req.Config.LogLevel.Value(),
		Logger:      req.Config.Logger,
	}

	req.Error = v2.Sign()

	if req.Error != nil {
		return
	}

	if req.HTTPRequest.Method == "POST" {
		// Set the body of the request based on the modified query parameters
		req.SetStringBody(v2.Query.Encode())

		// Now that the body has changed, remove any Content-Length header,
		// because it will be incorrect
		req.HTTPRequest.ContentLength = 0
		req.HTTPRequest.Header.Del("Content-Length")
	} else {
		req.HTTPRequest.URL.RawQuery = v2.Query.Encode()
	}
}
1224277
func FromRequest(r *http.Request) (*Signature, error) {
	if s, ok := r.Header[headerSignature]; ok {
		return FromString(s[0])
	}
	if a, ok := r.Header[headerAuthorization]; ok {
		return FromString(strings.TrimPrefix(a[0], authScheme))
	}
	return nil, ErrorNoSignatureHeader
}
1293480
func (k SigningSecretKey) Sign(msg []byte) (ret []byte, err error) {
	return ed25519.Sign(k.sec[:], msg), nil
}
263775
func (r *Request) SignQuery(timeoutSeconds int) error {
	err := r.signQuery(int(time.Now().Unix()) + timeoutSeconds)
	if err != nil {
		return err
	}

	return nil
}
73410
func (s *SignatureScheme) Sign(cred []byte, sk handlers.Big, Nym handlers.Ecp, RNym handlers.Big, ipk handlers.IssuerPublicKey, attributes []bccsp.IdemixAttribute,
	msg []byte, rhIndex int, criRaw []byte) (res []byte, err error) {
	defer func() {
		if r := recover(); r != nil {
			res = nil
			err = errors.Errorf("failure [%s]", r)
		}
	}()

	isk, ok := sk.(*Big)
	if !ok {
		return nil, errors.Errorf("invalid user secret key, expected *Big, got [%T]", sk)
	}
	inym, ok := Nym.(*Ecp)
	if !ok {
		return nil, errors.Errorf("invalid nym public key, expected *Ecp, got [%T]", Nym)
	}
	irnym, ok := RNym.(*Big)
	if !ok {
		return nil, errors.Errorf("invalid nym secret key, expected *Big, got [%T]", RNym)
	}
	iipk, ok := ipk.(*IssuerPublicKey)
	if !ok {
		return nil, errors.Errorf("invalid issuer public key, expected *IssuerPublicKey, got [%T]", ipk)
	}

	credential := &cryptolib.Credential{}
	err = proto.Unmarshal(cred, credential)
	if err != nil {
		return nil, errors.Wrap(err, "failed unmarshalling credential")
	}

	cri := &cryptolib.CredentialRevocationInformation{}
	err = proto.Unmarshal(criRaw, cri)
	if err != nil {
		return nil, errors.Wrap(err, "failed unmarshalling credential revocation information")
	}

	disclosure := make([]byte, len(attributes))
	for i := 0; i < len(attributes); i++ {
		if attributes[i].Type == bccsp.IdemixHiddenAttribute {
			disclosure[i] = 0
		} else {
			disclosure[i] = 1
		}
	}

	sig, err := cryptolib.NewSignature(
		credential,
		isk.E,
		inym.E,
		irnym.E,
		iipk.PK,
		disclosure,
		msg,
		rhIndex,
		cri,
		s.NewRand())
	if err != nil {
		return nil, errors.WithMessage(err, "failed creating new signature")
	}

	return proto.Marshal(sig)
}
709741
func signatureV2(cred auth.Credentials, method string, encodedResource string, encodedQuery string, headers http.Header) string {
	stringToSign := getStringToSignV2(method, encodedResource, encodedQuery, headers, "")
	signature := calculateSignatureV2(stringToSign, cred.SecretKey)
	return signature
}
975895
func (s *JWTSigner) Sign(req *http.Request) error {
	return signFromSource(s.TokenSource, req)
}
1119881
func RequestSigning(id, key string) ClientOpt {
	return func(c *Client) {
		c.Handlers.Sign.Append(request.RequestSigner(id, key))
	}
}
282068
func (c *CertificateRequest) CheckSignature() error {
	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
}
966904
func (client *Client) Sign(method string, url string, req *http.Request, querys string) {

	header := req.Header

	var buf bytes.Buffer
	keys := make([]string, 0, len(header))
	for k := range header {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	buf.WriteString(method + HEADER_SEPERATER)
	for _, k := range keys {
		vs := header[k]
		//		prefix := strings.ToLower(k + ":")
		prefix := strings.ToLower(k + ":")
		for _, v := range vs {

			if v != "" {
				lowerKey := strings.ToLower(k)
				if strings.Contains(lowerKey, ACS_PREFIX) {
					buf.WriteString(prefix)
					buf.WriteString(v)
				} else {
					buf.WriteString(v)
				}

			}

			buf.WriteString("\n")
		}
	}

	//	写入url
	if querys != "" {
		url = url + "?" + querys
	}
	buf.WriteString(url)

	//fmt.Printf("SignString = %s ", buf.String())

	signiture := util.HmacSha1(client.GetAccessSecret(), buf.String())

	header.Add("Authorization", "acs "+client.GetAccessKey()+":"+signiture)
}
913164
func (ac AuthConfig) SignRequest(request *http.Request) error {
	// sanitize the path for the chef-server
	// chef-server doesn't support '//' in the Hash Path.
	var endpoint string
	if request.URL.Path != "" {
		endpoint = path.Clean(request.URL.Path)
		request.URL.Path = endpoint
	} else {
		endpoint = request.URL.Path
	}

	vals := map[string]string{
		"Method":             request.Method,
		"Hashed Path":        HashStr(endpoint),
		"Accept":             "application/json",
		"X-Chef-Version":     ChefVersion,
		"X-Ops-Timestamp":    time.Now().UTC().Format(time.RFC3339),
		"X-Ops-UserId":       ac.ClientName,
		"X-Ops-Sign":         "algorithm=sha1;version=1.0",
		"X-Ops-Content-Hash": request.Header.Get("X-Ops-Content-Hash"),
	}

	for _, key := range []string{"Method", "Accept", "X-Chef-Version", "X-Ops-Timestamp", "X-Ops-UserId", "X-Ops-Sign"} {
		request.Header.Set(key, vals[key])
	}

	// To validate the signature it seems to be very particular
	var content string
	for _, key := range []string{"Method", "Hashed Path", "X-Ops-Content-Hash", "X-Ops-Timestamp", "X-Ops-UserId"} {
		content += fmt.Sprintf("%s:%s\n", key, vals[key])
	}
	content = strings.TrimSuffix(content, "\n")
	// generate signed string of headers
	// Since we've gone through additional validation steps above,
	// we shouldn't get an error at this point
	signature, err := GenerateSignature(ac.PrivateKey, content)
	if err != nil {
		return err
	}

	// TODO: THIS IS CHEF PROTOCOL SPECIFIC
	// Signature is made up of n 60 length chunks
	base64sig := Base64BlockEncode(signature, 60)

	// roll over the auth slice and add the apropriate header
	for index, value := range base64sig {
		request.Header.Set(fmt.Sprintf("X-Ops-Authorization-%d", index+1), string(value))
	}

	return nil
}
227221
func (k *Client) signRequest(req *http.Request, t time.Time) {
	compliantDate := fmt.Sprintf(t.UTC().Format(time.RFC822Z))
	signingString := k.Method + "\n"

	d, readErr := ioutil.ReadAll(strings.NewReader(k.RawString))

	if readErr != nil {
		k.Logger.Fatal(readErr)
	}

	switch k.Method {
	case POST, PUT, PATCH:
		md5Sum := md5.Sum(d)
		req.Header.Set("Content-MD5", fmt.Sprintf("%x", string(md5Sum[:16])))

		signingString += fmt.Sprintf("content-md5:%v\n", req.Header.Get("Content-MD5"))
		signingString += fmt.Sprintf("content-type:%v\n", req.Header.Get("Content-Type"))
	}

	if k.ProxyRequestData != nil {
		req.Header.Set("Proxy-Authorization", genProxyRequestHeader(k.ProxyRequestData))
		signingString += fmt.Sprintf("proxy-authorization:%v\n", req.Header.Get("Proxy-Authorization"))

		if k.ProxyRequestData.Header.Get("X-Kumoru-Context") != "" {
			req.Header.Set("X-Kumoru-Context", k.ProxyRequestData.Header.Get("X-Kumoru-Context"))
			signingString += fmt.Sprintf("x-kumoru-context:%v\n", req.Header.Get("x-kumoru-context"))
		}

		k.Logger.Debug("signingString", signingString)
	}

	u, _ := url.Parse(k.URL)
	k.Logger.Debug("k.Url", k.URL)

	//There is a chicken and egg problem retrieving account information the first time.
	//The signing string cannot contain the context (RoleUUID) on the first request for account info.
	//Since the signing string logic is general purpose, it's easiest to skip this header for GET to .../accounts/...
	if strings.Contains(req.URL.Path, "/accounts/") == true && k.Method == "GET" {
		//pass
	} else {
		signingString += "x-kumoru-context:" + k.RoleUUID + "\n"
		req.Header.Set("X-Kumoru-Context", k.RoleUUID)
	}

	signingString += "x-kumoru-date:" + compliantDate + "\n" + u.Path
	req.Header.Set("X-Kumoru-Date", compliantDate)

	h := hmac.New(sha256.New, []byte(k.Tokens.Private))
	h.Write([]byte(signingString))
	digest := fmt.Sprintf("%x", h.Sum(nil))

	req.Header.Set("Authorization", base64.StdEncoding.EncodeToString([]byte(k.Tokens.Public+":"+digest)))
}
1082103
func (sc *SignerRemote) SignProposal(chainID string, proposal *types.Proposal) error {
	err := writeMsg(sc.conn, &SignProposalRequest{Proposal: proposal})
	if err != nil {
		return err
	}

	res, err := readMsg(sc.conn)
	if err != nil {
		return err
	}
	resp, ok := res.(*SignedProposalResponse)
	if !ok {
		return ErrUnexpectedResponse
	}
	if resp.Error != nil {
		return resp.Error
	}
	*proposal = *resp.Proposal

	return nil
}
725339
func (s *Service) Sign(request *http.Request, userConfig *UserConfig) error {
	return s.Signer.Sign(request, s.ClientConfig, userConfig)
}
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
}
1244869
func RequestSigner(id, key string) Handler {
	return Handler{
		Name: "RequestSigner",
		Fn: func(r *Request) {
			r.Error = httpsignatures.DefaultSha256Signer.SignRequest(id, key, r.HTTPRequest)
		},
	}
}
1117272
func (k SigningKey) SignForKBFS(data []byte) (SignatureInfo, error) {
	sigInfo, err := k.kp.SignV2(data, kbcrypto.SignaturePrefixKBFS)
	if err != nil {
		return SignatureInfo{}, errors.WithStack(err)
	}
	return SignatureInfo{
		Version:      SigVer(sigInfo.Version),
		Signature:    sigInfo.Sig[:],
		VerifyingKey: k.GetVerifyingKey(),
	}, nil
}