// genMAC generates the HMAC signature for a message provided the secret key
// and hashFunc.
970444
func genMAC(message, key []byte, hashFunc func() hash.Hash) []byte {
	mac := hmac.New(hashFunc, key)
	mac.Write(message)
	return mac.Sum(nil)
}
257757
func Gen(password string) string {
	salt := generateSalt(8)
	hash := generateHash(sha1.New, salt, password, 1)
	return "sha1$" + string(salt) + "$1$" + hash
}
16548
func CreateSignature(stringToSignature, accessKeySecret string) string {
	// Crypto by HMAC-SHA1
	hmacSha1 := hmac.New(sha1.New, []byte(accessKeySecret))
	hmacSha1.Write([]byte(stringToSignature))
	sign := hmacSha1.Sum(nil)

	// Encode to Base64
	base64Sign := base64.StdEncoding.EncodeToString(sign)

	return base64Sign
}
869901
func (c *HMACStrategy) Generate() (string, string, error) {
	c.Lock()
	defer c.Unlock()

	if len(c.GlobalSecret) < minimumSecretLength {
		return "", "", errors.Errorf("secret for signing HMAC-SHA256 is expected to be 32 byte long, got %d byte", len(c.GlobalSecret))
	}

	var signingKey [32]byte
	copy(signingKey[:], c.GlobalSecret)

	if c.TokenEntropy < minimumEntropy {
		c.TokenEntropy = minimumEntropy
	}

	// When creating secrets not intended for usage by human users (e.g.,
	// client secrets or token handles), the authorization server should
	// include a reasonable level of entropy in order to mitigate the risk
	// of guessing attacks.  The token value should be >=128 bits long and
	// constructed from a cryptographically strong random or pseudo-random
	// number sequence (see [RFC4086] for best current practice) generated
	// by the authorization server.
	tokenKey, err := RandomBytes(c.TokenEntropy)
	if err != nil {
		return "", "", errors.WithStack(err)
	}

	signature := generateHMAC(tokenKey, &signingKey)

	encodedSignature := b64.EncodeToString(signature)
	encodedToken := fmt.Sprintf("%s.%s", b64.EncodeToString(tokenKey), encodedSignature)
	return encodedToken, encodedSignature, nil
}
606034
func CheckPayloadSignature(payload []byte, secret string, signature string) (string, error) {
	signature = strings.TrimPrefix(signature, "sha1=")

	mac := hmac.New(sha1.New, []byte(secret))
	_, err := mac.Write(payload)
	if err != nil {
		return "", err
	}
	expectedMAC := hex.EncodeToString(mac.Sum(nil))

	if !hmac.Equal([]byte(signature), []byte(expectedMAC)) {
		return expectedMAC, &SignatureError{signature}
	}
	return expectedMAC, err
}
323567
func GenerateSignature(priv *rsa.PrivateKey, data string) (enc []byte, err error) {
	sig, err := privateEncrypt(priv, []byte(data))
	if err != nil {
		return nil, err
	}

	return sig, nil
}
799566
func computeHMAC256(key, message []byte) []byte {
	mac := hmac.New(sha256.New, key)
	mac.Write(message)
	return mac.Sum(nil)
}
477329
func messageTag(hash func() hash.Hash, km, msg, shared []byte) []byte {
	if shared == nil {
		shared = make([]byte, 0)
	}
	mac := hmac.New(hash, km)
	mac.Write(msg)
	tag := mac.Sum(nil)
	return tag
}
270093
func (c *Command) GenBashCompletionFile(filename string) error {
	outFile, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer outFile.Close()

	return c.GenBashCompletion(outFile)
}
714406
func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) {
	if keyBytes, ok := key.([]byte); ok {
		if !m.Hash.Available() {
			return "", ErrHashUnavailable
		}

		hasher := hmac.New(m.Hash.New, keyBytes)
		hasher.Write([]byte(signingString))

		return EncodeSegment(hasher.Sum(nil)), nil
	}

	return "", ErrInvalidKeyType
}
247246
func (j *JWT) KeyFunc(token *gojwt.Token) (interface{}, error) {
	if _, ok := token.Method.(*gojwt.SigningMethodHMAC); ok {
		return []byte(j.Secret), nil
	} else if _, ok := token.Method.(*gojwt.SigningMethodRSA); ok {
		return j.KeyFuncRS256(token)
	}
	return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
797856
func newCipherGeneric(key []byte) (Block, error) {
	n := len(key) + 28
	c := aesCipher{make([]uint32, n), make([]uint32, n)}
	expandKeyGo(key, c.enc, c.dec)
	return &c, nil
}
354292
func sign(message, key string) string {
	hashfun := hmac.New(sha1.New, []byte(key))
	hashfun.Write([]byte(message))
	rawsignature := hashfun.Sum(nil)
	base64signature := make([]byte, base64.StdEncoding.EncodedLen(len(rawsignature)))
	base64.StdEncoding.Encode(base64signature, rawsignature)

	return string(base64signature)
}
522176
func (pkz privKeys) GenFullCommit(chainID string, height int64, txs types.Txs,
	valset, nextValset *types.ValidatorSet, appHash, consHash, resHash []byte, first, last int) FullCommit {

	header := genHeader(chainID, height, txs, valset, nextValset, appHash, consHash, resHash)
	commit := types.SignedHeader{
		Header: header,
		Commit: pkz.signHeader(header, first, last),
	}
	return NewFullCommit(commit, valset, nextValset)
}
1259996
func HmacSHA512(key, origData []byte) (sum []byte) {
	mac := hmac.New(sha512.New, key)
	mac.Write(origData)
	return mac.Sum(nil)
}
1088373
func DefaultHMAC(key, buf []byte) (HMAC, error) {
	mac := hmac.New(DefaultHashNew, key)
	mac.Write(buf)
	h, err := HashFromRaw(DefaultHashType, mac.Sum(nil))
	if err != nil {
		return HMAC{}, err
	}
	return HMAC{h}, nil
}
27094
func GenDoc(ctx *cli.Context) {

	var (
		a    = common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef")
		b    = common.HexToAddress("0x1111111122222222222233333333334444444444")
		meta = core.Metadata{
			Scheme:    "http",
			Local:     "localhost:8545",
			Origin:    "www.malicious.ru",
			Remote:    "localhost:9999",
			UserAgent: "Firefox 3.2",
		}
		output []string
		add    = func(name, desc string, v interface{}) {
			if data, err := json.MarshalIndent(v, "", "  "); err == nil {
				output = append(output, fmt.Sprintf("### %s\n\n%s\n\nExample:\n```json\n%s\n```", name, desc, data))
			} else {
				log.Error("Error generating output", err)
			}
		}
	)

	{ // Sign plain text request
		desc := "SignDataRequest contains information about a pending request to sign some data. " +
			"The data to be signed can be of various types, defined by content-type. Clef has done most " +
			"of the work in canonicalizing and making sense of the data, and it's up to the UI to present" +
			"the user with the contents of the `message`"
		sighash, msg := accounts.TextAndHash([]byte("hello world"))
		message := []*core.NameValueType{{"message", msg, accounts.MimetypeTextPlain}}

		add("SignDataRequest", desc, &core.SignDataRequest{
			Address:     common.NewMixedcaseAddress(a),
			Meta:        meta,
			ContentType: accounts.MimetypeTextPlain,
			Rawdata:     []byte(msg),
			Message:     message,
			Hash:        sighash})
	}
	{ // Sign plain text response
		add("SignDataResponse - approve", "Response to SignDataRequest",
			&core.SignDataResponse{Approved: true})
		add("SignDataResponse - deny", "Response to SignDataRequest",
			&core.SignDataResponse{})
	}
	{ // Sign transaction request
		desc := "SignTxRequest contains information about a pending request to sign a transaction. " +
			"Aside from the transaction itself, there is also a `call_info`-struct. That struct contains " +
			"messages of various types, that the user should be informed of." +
			"\n\n" +
			"As in any request, it's important to consider that the `meta` info also contains untrusted data." +
			"\n\n" +
			"The `transaction` (on input into clef) can have either `data` or `input` -- if both are set, " +
			"they must be identical, otherwise an error is generated. " +
			"However, Clef will always use `data` when passing this struct on (if Clef does otherwise, please file a ticket)"

		data := hexutil.Bytes([]byte{0x01, 0x02, 0x03, 0x04})
		add("SignTxRequest", desc, &core.SignTxRequest{
			Meta: meta,
			Callinfo: []core.ValidationInfo{
				{"Warning", "Something looks odd, show this message as a warning"},
				{"Info", "User should see this aswell"},
			},
			Transaction: core.SendTxArgs{
				Data:     &data,
				Nonce:    0x1,
				Value:    hexutil.Big(*big.NewInt(6)),
				From:     common.NewMixedcaseAddress(a),
				To:       nil,
				GasPrice: hexutil.Big(*big.NewInt(5)),
				Gas:      1000,
				Input:    nil,
			}})
	}
	{ // Sign tx response
		data := hexutil.Bytes([]byte{0x04, 0x03, 0x02, 0x01})
		add("SignTxResponse - approve", "Response to request to sign a transaction. This response needs to contain the `transaction`"+
			", because the UI is free to make modifications to the transaction.",
			&core.SignTxResponse{Approved: true,
				Transaction: core.SendTxArgs{
					Data:     &data,
					Nonce:    0x4,
					Value:    hexutil.Big(*big.NewInt(6)),
					From:     common.NewMixedcaseAddress(a),
					To:       nil,
					GasPrice: hexutil.Big(*big.NewInt(5)),
					Gas:      1000,
					Input:    nil,
				}})
		add("SignTxResponse - deny", "Response to SignTxRequest. When denying a request, there's no need to "+
			"provide the transaction in return",
			&core.SignTxResponse{})
	}
	{ // WHen a signed tx is ready to go out
		desc := "SignTransactionResult is used in the call `clef` -> `OnApprovedTx(result)`" +
			"\n\n" +
			"This occurs _after_ successful completion of the entire signing procedure, but right before the signed " +
			"transaction is passed to the external caller. This method (and data) can be used by the UI to signal " +
			"to the user that the transaction was signed, but it is primarily useful for ruleset implementations." +
			"\n\n" +
			"A ruleset that implements a rate limitation needs to know what transactions are sent out to the external " +
			"interface. By hooking into this methods, the ruleset can maintain track of that count." +
			"\n\n" +
			"**OBS:** Note that if an attacker can restore your `clef` data to a previous point in time" +
			" (e.g through a backup), the attacker can reset such windows, even if he/she is unable to decrypt the content. " +
			"\n\n" +
			"The `OnApproved` method cannot be responded to, it's purely informative"

		rlpdata := common.FromHex("0xf85d640101948a8eafb1cf62bfbeb1741769dae1a9dd47996192018026a0716bd90515acb1e68e5ac5867aa11a1e65399c3349d479f5fb698554ebc6f293a04e8a4ebfff434e971e0ef12c5bf3a881b06fd04fc3f8b8a7291fb67a26a1d4ed")
		var tx types.Transaction
		rlp.DecodeBytes(rlpdata, &tx)
		add("OnApproved - SignTransactionResult", desc, &ethapi.SignTransactionResult{Raw: rlpdata, Tx: &tx})

	}
	{ // User input
		add("UserInputRequest", "Sent when clef needs the user to provide data. If 'password' is true, the input field should be treated accordingly (echo-free)",
			&core.UserInputRequest{IsPassword: true, Title: "The title here", Prompt: "The question to ask the user"})
		add("UserInputResponse", "Response to UserInputRequest",
			&core.UserInputResponse{Text: "The textual response from user"})
	}
	{ // List request
		add("ListRequest", "Sent when a request has been made to list addresses. The UI is provided with the "+
			"full `account`s, including local directory names. Note: this information is not passed back to the external caller, "+
			"who only sees the `address`es. ",
			&core.ListRequest{
				Meta: meta,
				Accounts: []accounts.Account{
					{a, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/a"}},
					{b, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/b"}}},
			})

		add("ListResponse", "Response to list request. The response contains a list of all addresses to show to the caller. "+
			"Note: the UI is free to respond with any address the caller, regardless of whether it exists or not",
			&core.ListResponse{
				Accounts: []accounts.Account{
					{common.HexToAddress("0xcowbeef000000cowbeef00000000000000000c0w"), accounts.URL{Path: ".. ignored .."}},
					{common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff"), accounts.URL{}},
				}})
	}

	fmt.Println(`## UI Client interface

These data types are defined in the channel between clef and the UI`)
	for _, elem := range output {
		fmt.Println(elem)
	}
}