// Create a ledger key for an individual delegated output in a token transaction, as a function of
// the transaction ID, and the index of the output
553412
func createDelegatedOutputKey(txID string, index int) (string, error) {
	return createCompositeKey(tokenDelegatedOutput, []string{txID, strconv.Itoa(index)})
}
446530
func (k *Kontrol) generateToken(tok *token) (string, error) {
	uniqKey := tok.String()

	k.tokenCacheMu.Lock()
	defer k.tokenCacheMu.Unlock()

	if !tok.force {
		if ct, ok := k.tokenCache[uniqKey]; ok {
			return ct.signed, nil
		}
	}

	rsaPrivate, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(tok.keyPair.Private))
	if err != nil {
		return "", err
	}

	id, err := uuid.NewV4()
	if err != nil {
		return "", err
	}

	now := time.Now().UTC()

	claims := &kitekey.KiteClaims{
		StandardClaims: jwt.StandardClaims{
			Issuer:    tok.issuer,
			Subject:   tok.username,
			Audience:  tok.audience,
			ExpiresAt: now.Add(k.tokenTTL()).Add(k.tokenLeeway()).UTC().Unix(),
			IssuedAt:  now.Add(-k.tokenLeeway()).UTC().Unix(),
			Id:        id.String(),
		},
	}

	if !k.TokenNoNBF {
		claims.NotBefore = now.Add(-k.tokenLeeway()).Unix()
	}

	signed, err := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims).SignedString(rsaPrivate)
	if err != nil {
		return "", errors.New("Server error: Cannot generate a token")
	}

	k.cacheToken(uniqKey, signed)

	return signed, nil
}
286232
func (auth *Auth) CreateCustomToken(userID string, claims interface{}) (string, error) {
	if auth.app.privateKey == nil {
		return "", ErrRequireServiceAccount
	}
	now := time.Now()
	payload := &customClaims{
		Issuer:    auth.app.clientEmail,
		Subject:   auth.app.clientEmail,
		Audience:  customTokenAudience,
		IssuedAt:  now.Unix(),
		ExpiresAt: now.Add(time.Hour).Unix(),
		UserID:    userID,
		Claims:    claims,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, payload)
	return token.SignedString(auth.app.privateKey)
}
881756
func GenerateSecretKey() []byte {
	secretData := make([]byte, naclSecretboxKeySize)
	if _, err := io.ReadFull(cryptorand.Reader, secretData); err != nil {
		// panic if we can't read random data
		panic(errors.Wrap(err, "failed to read random bytes"))
	}
	return secretData
}
644576
func (tpc *TwoPC) CreateTransaction(ctx context.Context, conn *TxConnection, dtid string, participants []*querypb.Target) error {
	bindVars := map[string]*querypb.BindVariable{
		"dtid":     sqltypes.StringBindVariable(dtid),
		"state":    sqltypes.Int64BindVariable(int64(DTStatePrepare)),
		"cur_time": sqltypes.Int64BindVariable(time.Now().UnixNano()),
	}
	_, err := tpc.exec(ctx, conn, tpc.insertTransaction, bindVars)
	if err != nil {
		return err
	}

	rows := make([][]sqltypes.Value, len(participants))
	for i, participant := range participants {
		rows[i] = []sqltypes.Value{
			sqltypes.NewVarBinary(dtid),
			sqltypes.NewInt64(int64(i + 1)),
			sqltypes.NewVarBinary(participant.Keyspace),
			sqltypes.NewVarBinary(participant.Shard),
		}
	}
	extras := map[string]sqlparser.Encodable{
		"vals": sqlparser.InsertValues(rows),
	}
	q, err := tpc.insertParticipants.GenerateQuery(nil, extras)
	if err != nil {
		return err
	}
	_, err = conn.Exec(ctx, q, 1, false)
	return err
}
457135
func generateKeyPair(private string) error {
	out, err := exec.Command(
		"ssh-keygen",
		"-q",        // silence
		"-t", "dsa", // type
		"-b", "1024", // length in bits
		"-f", private, // output file
		"-N", "", // no passphrase
	).Output()
	if err != nil {
		// out is in form of bytes buffer and we have to turn it into slice ending on first \0 occurrence
		return fmt.Errorf("error in keygen time. ret_val: %v, output: %v", err, string(out[:]))
	}
	return nil
}
1109139
func chainedPrivKey(privkey, pubkey, chaincode []byte) ([]byte, error) {
	if len(privkey) != 32 {
		return nil, fmt.Errorf("invalid privkey length %d (must be 32)",
			len(privkey))
	}
	if len(chaincode) != 32 {
		return nil, fmt.Errorf("invalid chaincode length %d (must be 32)",
			len(chaincode))
	}
	switch n := len(pubkey); n {
	case btcec.PubKeyBytesLenUncompressed, btcec.PubKeyBytesLenCompressed:
		// Correct length
	default:
		return nil, fmt.Errorf("invalid pubkey length %d", n)
	}

	xorbytes := make([]byte, 32)
	chainMod := chainhash.DoubleHashB(pubkey)
	for i := range xorbytes {
		xorbytes[i] = chainMod[i] ^ chaincode[i]
	}
	chainXor := new(big.Int).SetBytes(xorbytes)
	privint := new(big.Int).SetBytes(privkey)

	t := new(big.Int).Mul(chainXor, privint)
	b := t.Mod(t, btcec.S256().N).Bytes()
	return pad(32, b), nil
}
489115
func Key(password, salt []byte, iterations, parallelism, memory uint32, keyLength int, variant Variant) ([]byte, error) {
	// Prepare an output slice
	output := make([]byte, keyLength)

	ctx := &context{
		out:        output,
		pwd:        password,
		salt:       salt,
		timeCost:   iterations,
		memoryCost: memory,
		lanes:      parallelism,
		threads:    parallelism,
	}

	if err := core(ctx, variant); err != nil {
		return nil, err
	}

	return output, nil
}
686050
func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error) {
	return GenerateMultiPrimeKey(random, 2, bits)
}
1154480
func (handle *ContextHandle) GenerateKey(session mPkcs11.SessionHandle, m []*mPkcs11.Mechanism, temp []*mPkcs11.Attribute) (mPkcs11.ObjectHandle, error) {

	handle.lock.RLock()
	defer handle.lock.RUnlock()

	return handle.ctx.GenerateKey(session, m, temp)
}
1266508
func (v *Verifier) commitTransferAction(transferAction *token.PlainTransfer, txID string, simulator ledger.LedgerWriter) error {
	var outputID string
	var err error
	for i, output := range transferAction.GetOutputs() {
		if output.Owner != nil {
			outputID, err = createOutputKey(txID, i)
		} else {
			outputID, err = createRedeemKey(txID, i)
		}
		if err != nil {
			return &customtx.InvalidTxError{Msg: fmt.Sprintf("error creating output ID: %s", err)}
		}

		err = v.addOutput(outputID, output, simulator)
		if err != nil {
			return err
		}
	}
	return v.markInputsSpent(txID, transferAction.GetInputs(), simulator)
}
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"])
}
1157020
func GenerateKey(algorithm string) (data.PrivateKey, error) {
	switch algorithm {
	case data.ECDSAKey:
		return GenerateECDSAKey(rand.Reader)
	case data.ED25519Key:
		return GenerateED25519Key(rand.Reader)
	}
	return nil, fmt.Errorf("private key type not supported for key generation: %s", algorithm)
}
1078352
func CreateToken(t testing.T, state StateStore, index uint64, policies []string) *structs.ACLToken {
	t.Helper()

	// Create the ACLToken
	token := ACLToken()
	token.Policies = policies
	token.SetHash()
	assert.Nil(t, state.UpsertACLTokens(index, []*structs.ACLToken{token}))
	return token
}
1318550
func (m *tokenManager) PublicKey(keyID string) *rsa.PublicKey {
	return m.publicKeysMap[keyID]
}
601521
func (x *XC) ExportPrivateKey(ctx context.Context, id string) ([]byte, error) {
	return x.secring.Export(id, true)
}
1251366
func (a *ACLTokens) Create(token *ACLToken, q *WriteOptions) (*ACLToken, *WriteMeta, error) {
	if token.AccessorID != "" {
		return nil, nil, fmt.Errorf("cannot specify Accessor ID")
	}
	var resp ACLToken
	wm, err := a.client.write("/v1/acl/token", token, &resp, q)
	if err != nil {
		return nil, nil, err
	}
	return &resp, wm, nil
}