// Create a ledger key for a spent individual delegated output in a token transaction, as a function of
// the transaction ID, and the index of the delegated output
559406
func createSpentDelegatedOutputKey(txID string, index int) (string, error) {
	return createCompositeKey(tokenDelegatedInput, []string{txID, strconv.Itoa(index)})
}
1100804
func (m *Mocker) CreatePrivateKeyBatch(ctx context.Context, name, email, pw string) error {
	return fmt.Errorf("not yet implemented")
}
925419
func (g *GPG) CreatePrivateKeyBatch(ctx context.Context, name, email, pw string) error {
	ent, err := openpgp.NewEntity(name, "", email, &packet.Config{
		RSABits: 4096,
	})
	if err != nil {
		return err
	}
	g.secring = append(g.secring, ent)
	return g.saveSecring()
}
899926
func (g *GPG) CreatePrivateKey(ctx context.Context) error {
	args := []string{"--gen-key"}
	cmd := exec.CommandContext(ctx, g.binary, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	out.Debug(ctx, "gpg.CreatePrivateKey: %s %+v", cmd.Path, cmd.Args)
	if err := cmd.Run(); err != nil {
		return errors.Wrapf(err, "failed to run command: '%s %+v'", cmd.Path, cmd.Args)
	}

	g.privKeys = nil
	g.pubKeys = nil
	return nil
}
1219866
func (rlf *ramLedgerFactory) GetOrCreate(chainID string) (blockledger.ReadWriter, error) {
	rlf.mutex.Lock()
	defer rlf.mutex.Unlock()

	key := chainID

	l, ok := rlf.ledgers[key]
	if ok {
		return l, nil
	}

	ch := newChain(rlf.maxSize)
	rlf.ledgers[key] = ch
	return ch, nil
}
572018
func GeneratePrivateKey() [keySize]byte {
	var b [keySize]byte
	rand.Read(b[:])

	return b
}
490261
func generatePrivateKey(algorithm string) (data.PrivateKey, error) {
	var privKey data.PrivateKey
	var err error
	switch algorithm {
	case data.ECDSAKey:
		privKey, err = utils.GenerateECDSAKey(rand.Reader)
		if err != nil {
			return nil, fmt.Errorf("failed to generate EC key: %v", err)
		}
	case data.ED25519Key:
		privKey, err = utils.GenerateED25519Key(rand.Reader)
		if err != nil {
			return nil, fmt.Errorf("failed to generate ED25519 key: %v", err)
		}
	default:
		return nil, fmt.Errorf("private key type not supported for key generation: %s", algorithm)
	}
	return privKey, 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)
}
463834
func GenerateKey(rand io.Reader) (publicKey, privateKey nacl.Key, err error) {
	privateKey = new([32]byte)
	_, err = io.ReadFull(rand, privateKey[:])
	if err != nil {
		publicKey = nil
		privateKey = nil
		return
	}

	publicKey = scalarmult.Base(privateKey)
	return publicKey, privateKey, nil
}
543643
func NewKeyForDirectICAP(rand io.Reader) *Key {
	randBytes := make([]byte, 64)
	_, err := rand.Read(randBytes)
	if err != nil {
		panic("key generation: could not read from random source: " + err.Error())
	}
	reader := bytes.NewReader(randBytes)
	privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), reader)
	if err != nil {
		panic("key generation: ecdsa.GenerateKey failed: " + err.Error())
	}
	key := newKeyFromECDSA(privateKeyECDSA)
	if !strings.HasPrefix(key.Address.Hex(), "0x00") {
		return NewKeyForDirectICAP(rand)
	}
	return key
}
558357
func (b *BtcWallet) fetchPrivKey(keyDesc *keychain.KeyDescriptor) (*btcec.PrivateKey, error) {
	// If the key locator within the descriptor *isn't* empty, then we can
	// directly derive the keys raw.
	if !keyDesc.KeyLocator.IsEmpty() {
		// We'll assume the special lightning key scope in this case.
		scopedMgr, err := b.wallet.Manager.FetchScopedKeyManager(
			b.chainKeyScope,
		)
		if err != nil {
			return nil, err
		}

		var key *btcec.PrivateKey
		err = walletdb.View(b.db, func(tx walletdb.ReadTx) error {
			addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)

			path := waddrmgr.DerivationPath{
				Account: uint32(keyDesc.Family),
				Branch:  0,
				Index:   uint32(keyDesc.Index),
			}
			addr, err := scopedMgr.DeriveFromKeyPath(addrmgrNs, path)
			if err != nil {
				return err
			}

			key, err = addr.(waddrmgr.ManagedPubKeyAddress).PrivKey()
			return err
		})
		if err != nil {
			return nil, err
		}

		return key, nil
	}

	hash160 := btcutil.Hash160(keyDesc.PubKey.SerializeCompressed())
	addr, err := btcutil.NewAddressWitnessPubKeyHash(hash160, b.netParams)
	if err != nil {
		return nil, err
	}

	return b.wallet.PrivKeyForAddress(addr)
}
1058121
func (instance *PublicKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) {
	if err := AssertPublicKeyAndTokenCombination(instance.publicKey, token); err != nil {
		return nil, err
	}
	return instance.publicKey, nil
}
56456
func generateToken(c context.Context) (string, error) {
	logging.Warningf(c, "%q is generating pprof token", auth.CurrentIdentity(c))
	return pprofToken.Generate(c, nil, nil, 0)
}
427595
func (m *Machine) CreateToken(ctx context.Context, notifier *observer.Notifier,
	machine *envelope.Machine, secret *base64.Value) (*registry.MachineTokenCreationSegment, error) {
	n := notifier.Notifier(2)

	n.Notify(observer.Progress, "Generating machine token", true)
	salt, err := crypto.GenerateSalt(ctx)
	if err != nil {
		return nil, err
	}

	keypair, err := crypto.DeriveLoginKeypair(ctx, *secret, salt)
	if err != nil {
		return nil, err
	}

	orgID := machine.Body.OrgID

	masterKey, err := crypto.CreateMasterKeyObject(ctx, *secret, nil)
	if err != nil {
		return nil, err
	}

	tokenBody := &primitive.MachineToken{
		OrgID:     orgID,
		MachineID: machine.ID,
		PublicKey: &primitive.LoginPublicKey{
			Salt:  keypair.Salt(),
			Value: keypair.PublicKey(),
			Alg:   crypto.EdDSA,
		},
		Master:      masterKey,
		CreatedBy:   m.engine.session.ID(),
		Created:     time.Now().UTC(),
		DestroyedBy: nil,
		Destroyed:   nil,
		State:       primitive.MachineTokenActiveState,
	}
	tokenID, err := identity.NewMutable(tokenBody)
	if err != nil {
		return nil, err
	}

	token := &envelope.MachineToken{
		ID:      &tokenID,
		Version: 1,
		Body:    tokenBody,
	}

	// Create an "empty" machine session in order to create a Crypto engine on
	// behalf of the machine for deriving and uploading these keys.
	sess := session.NewSession(m.engine.guard)
	err = sess.Set(apitypes.MachineSession, machine, token, *secret, []byte("hello"))
	if err != nil {
		return nil, err
	}
	c := crypto.NewEngine(sess, m.engine.guard)

	n.Notify(observer.Progress, "Generating token keypairs", true)
	kp, err := c.GenerateKeyPairs(ctx)
	if err != nil {
		log.Printf("Error generating machine keypairs: %s", err)
		return nil, err
	}

	authID := sess.AuthID()
	keypairs, err := generateKeypairs(ctx, c, orgID, authID, kp)
	if err != nil {
		return nil, err
	}

	return &registry.MachineTokenCreationSegment{
		Token:    token,
		Keypairs: keypairs,
	}, nil
}
325671
func (m *ExpirationManager) createIndexByToken(ctx context.Context, le *leaseEntry, token string) error {
	tokenNS := namespace.RootNamespace
	saltCtx := namespace.ContextWithNamespace(ctx, namespace.RootNamespace)
	_, nsID := namespace.SplitIDFromString(token)
	if nsID != "" {
		tokenNS, err := NamespaceByID(ctx, nsID, m.core)
		if err != nil {
			return err
		}
		if tokenNS != nil {
			saltCtx = namespace.ContextWithNamespace(ctx, tokenNS)
		}
	}

	saltedID, err := m.tokenStore.SaltID(saltCtx, token)
	if err != nil {
		return err
	}

	leaseSaltedID, err := m.tokenStore.SaltID(saltCtx, le.LeaseID)
	if err != nil {
		return err
	}

	ent := logical.StorageEntry{
		Key:   saltedID + "/" + leaseSaltedID,
		Value: []byte(le.LeaseID),
	}
	tokenView := m.tokenIndexView(tokenNS)
	if err := tokenView.Put(ctx, &ent); err != nil {
		return errwrap.Wrapf("failed to persist lease index entry: {{err}}", err)
	}
	return nil
}
495786
func (s *KeyManagementServer) CreateKey(ctx context.Context, req *pb.CreateKeyRequest) (*pb.PublicKey, error) {
	service := s.CryptoServices[req.Algorithm]

	logger := ctxu.GetLogger(ctx)

	if service == nil {
		logger.Error("CreateKey: unsupported algorithm: ", req.Algorithm)
		return nil, fmt.Errorf("algorithm %s not supported for create key", req.Algorithm)
	}

	var tufKey data.PublicKey
	var err error

	tufKey, err = service.Create(data.RoleName(req.Role), data.GUN(req.Gun), req.Algorithm)
	if err != nil {
		logger.Error("CreateKey: failed to create key: ", err)
		return nil, grpc.Errorf(codes.Internal, "Key creation failed")
	}
	logger.Info("CreateKey: Created KeyID ", tufKey.ID())

	return &pb.PublicKey{
		KeyInfo: &pb.KeyInfo{
			KeyID:     &pb.KeyID{ID: tufKey.ID()},
			Algorithm: &pb.Algorithm{Algorithm: tufKey.Algorithm()},
		},
		PublicKey: tufKey.Public(),
	}, nil
}
563325
func CreateChainFromBlock(cb *common.Block, ccp ccprovider.ChaincodeProvider, sccp sysccprovider.SystemChaincodeProvider) error {
	cid, err := utils.GetChainIDFromBlock(cb)
	if err != nil {
		return err
	}

	var l ledger.PeerLedger
	if l, err = ledgermgmt.CreateLedger(cb); err != nil {
		return errors.WithMessage(err, "cannot create ledger from genesis block")
	}

	return createChain(cid, l, cb, ccp, sccp, pluginMapper)
}