// GetTLFCryptKeyOfAllGenerations implements the KeyManager interface for
// KeyManagerStandard.
763309
func (km *KeyManagerStandard) GetTLFCryptKeyOfAllGenerations(
	ctx context.Context, kmd libkey.KeyMetadata) (
	keys []kbfscrypto.TLFCryptKey, err error) {
	for g := kbfsmd.FirstValidKeyGen; g <= kmd.LatestKeyGeneration(); g++ {
		var key kbfscrypto.TLFCryptKey
		key, err = km.getTLFCryptKeyUsingCurrentDevice(ctx, kmd, g, true)
		if err != nil {
			return keys, err
		}
		keys = append(keys, key)
	}
	return keys, nil
}
143082
func (md *RootMetadataV2) GetHistoricTLFCryptKey(
	_ kbfscodec.Codec, _ KeyGen, _ kbfscrypto.TLFCryptKey, _ ExtraMetadata) (
	kbfscrypto.TLFCryptKey, error) {
	return kbfscrypto.TLFCryptKey{}, errors.New(
		"TLF crypt key not symmetrically encrypted")
}
122210
func (md *RootMetadataV2) getTLFKeyBundles(keyGen KeyGen) (
	*TLFWriterKeyBundleV2, *TLFReaderKeyBundleV2, error) {
	if md.ID.Type() != tlf.Private {
		return nil, nil, InvalidNonPrivateTLFOperation{md.ID, "getTLFKeyBundles", md.Version()}
	}

	if keyGen < FirstValidKeyGen {
		return nil, nil, InvalidKeyGenerationError{md.ID, keyGen}
	}
	i := int(keyGen - FirstValidKeyGen)
	if i >= len(md.WKeys) || i >= len(md.RKeys) {
		return nil, nil, NewKeyGenerationError{md.ID, keyGen}
	}
	return &md.WKeys[i], &md.RKeys[i], nil
}
1098499
func splitTLFCryptKey(uid keybase1.UID,
	tlfCryptKey kbfscrypto.TLFCryptKey,
	ePrivKey kbfscrypto.TLFEphemeralPrivateKey, ePubIndex int,
	pubKey kbfscrypto.CryptPublicKey) (
	TLFCryptKeyInfo, kbfscrypto.TLFCryptKeyServerHalf, error) {
	//    * create a new random server half
	//    * mask it with the key to get the client half
	//    * encrypt the client half
	var serverHalf kbfscrypto.TLFCryptKeyServerHalf
	serverHalf, err := kbfscrypto.MakeRandomTLFCryptKeyServerHalf()
	if err != nil {
		return TLFCryptKeyInfo{}, kbfscrypto.TLFCryptKeyServerHalf{}, err
	}

	clientHalf := kbfscrypto.MaskTLFCryptKey(serverHalf, tlfCryptKey)

	var encryptedClientHalf kbfscrypto.EncryptedTLFCryptKeyClientHalf
	encryptedClientHalf, err =
		kbfscrypto.EncryptTLFCryptKeyClientHalf(ePrivKey, pubKey, clientHalf)
	if err != nil {
		return TLFCryptKeyInfo{}, kbfscrypto.TLFCryptKeyServerHalf{}, err
	}

	var serverHalfID kbfscrypto.TLFCryptKeyServerHalfID
	serverHalfID, err =
		kbfscrypto.MakeTLFCryptKeyServerHalfID(uid, pubKey, serverHalf)
	if err != nil {
		return TLFCryptKeyInfo{}, kbfscrypto.TLFCryptKeyServerHalf{}, err
	}

	clientInfo := TLFCryptKeyInfo{
		ClientHalf:   encryptedClientHalf,
		ServerHalfID: serverHalfID,
		EPubKeyIndex: ePubIndex,
	}
	return clientInfo, serverHalf, nil
}
1034457
func (md *MDServerDisk) GetKeyBundles(ctx context.Context,
	tlfID tlf.ID, wkbID kbfsmd.TLFWriterKeyBundleID, rkbID kbfsmd.TLFReaderKeyBundleID) (
	*kbfsmd.TLFWriterKeyBundleV3, *kbfsmd.TLFReaderKeyBundleV3, error) {
	if err := checkContext(ctx); err != nil {
		return nil, nil, err
	}

	tlfStorage, err := md.getStorage(tlfID)
	if err != nil {
		return nil, nil, err
	}

	return tlfStorage.getKeyBundles(tlfID, wkbID, rkbID)
}
114634
func (km *KeyManagerStandard) GetTLFCryptKeyForEncryption(ctx context.Context,
	kmd libkey.KeyMetadata) (tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
	return km.getTLFCryptKeyUsingCurrentDevice(ctx, kmd,
		kmd.LatestKeyGeneration(), false)
}
505087
func (md *RootMetadataV2) AddKeyGeneration(
	codec kbfscodec.Codec, extra ExtraMetadata,
	updatedWriterKeys, updatedReaderKeys UserDevicePublicKeys,
	ePubKey kbfscrypto.TLFEphemeralPublicKey,
	ePrivKey kbfscrypto.TLFEphemeralPrivateKey,
	pubKey kbfscrypto.TLFPublicKey,
	currCryptKey, nextCryptKey kbfscrypto.TLFCryptKey) (
	nextExtra ExtraMetadata,
	serverHalves UserDeviceKeyServerHalves, err error) {
	if md.TlfID().Type() != tlf.Private {
		return nil, nil, InvalidNonPrivateTLFOperation{
			md.TlfID(), "AddKeyGeneration", md.Version()}
	}

	if len(updatedWriterKeys) == 0 {
		return nil, nil, errors.New(
			"updatedWriterKeys unexpectedly non-empty")
	}

	if currCryptKey != (kbfscrypto.TLFCryptKey{}) {
		return nil, nil, errors.New("currCryptKey unexpectedly non-zero")
	}

	if len(md.WKeys) != len(md.RKeys) {
		return nil, nil, fmt.Errorf(
			"Have %d writer key gens, but %d reader key gens",
			len(md.WKeys), len(md.RKeys))
	}

	if len(md.WKeys) > 0 {
		existingWriterKeys :=
			md.WKeys[len(md.WKeys)-1].WKeys.ToPublicKeys()
		if !existingWriterKeys.Equals(updatedWriterKeys) {
			return nil, nil, fmt.Errorf(
				"existingWriterKeys=%+v != updatedWriterKeys=%+v",
				existingWriterKeys, updatedWriterKeys)
		}

		existingReaderKeys :=
			md.RKeys[len(md.RKeys)-1].RKeys.ToPublicKeys()
		if !existingReaderKeys.Equals(updatedReaderKeys) {
			return nil, nil, fmt.Errorf(
				"existingReaderKeys=%+v != updatedReaderKeys=%+v",
				existingReaderKeys, updatedReaderKeys)
		}
	}

	newWriterKeys := TLFWriterKeyBundleV2{
		WKeys:        make(UserDeviceKeyInfoMapV2),
		TLFPublicKey: pubKey,
	}
	md.WKeys = append(md.WKeys, newWriterKeys)

	newReaderKeys := TLFReaderKeyBundleV2{
		RKeys: make(UserDeviceKeyInfoMapV2),
	}
	md.RKeys = append(md.RKeys, newReaderKeys)

	serverHalves, err = md.updateKeyGeneration(
		md.LatestKeyGeneration(), updatedWriterKeys,
		updatedReaderKeys, ePubKey, ePrivKey, nextCryptKey)
	if err != nil {
		return nil, nil, err
	}

	return nil, serverHalves, nil
}
902770
func BenchmarkKeyGeneration(b *testing.B, GenerateKey func(reader io.Reader) crypto.PrivKey) {
	var zero zeroReader
	for i := 0; i < b.N; i++ {
		GenerateKey(zero)
	}
}
10277
func GetGenericCredential(targetName string) (*GenericCredential, error) {
	cred, err := sysCredRead(targetName, sysCRED_TYPE_GENERIC)
	if cred != nil {
		return &GenericCredential{*cred}, err
	}
	return nil, err
}
1092662
func (c *ConfigLocal) GetAllSyncedTlfs() []tlf.ID {
	c.lock.RLock()
	defer c.lock.RUnlock()
	tlfs := make([]tlf.ID, 0, len(c.syncedTlfs))
	for tlf, config := range c.syncedTlfs {
		if config.Mode != keybase1.FolderSyncMode_DISABLED {
			tlfs = append(tlfs, tlf)
		}
	}
	return tlfs
}
822035
func (s *PerUserKeyring) CurrentGeneration() keybase1.PerUserKeyGeneration {
	s.Lock()
	defer s.Unlock()
	return s.currentGenerationLocked()
}
52077
func (c *CryptoClient) DecryptTLFCryptKeyClientHalfAny(ctx context.Context,
	keys []EncryptedTLFCryptKeyClientAndEphemeral, promptPaper bool) (
	clientHalf kbfscrypto.TLFCryptKeyClientHalf, index int, err error) {
	c.log.CDebugf(ctx, "Decrypting TLF client key half with any key")
	defer func() {
		c.deferLog.CDebugf(ctx,
			"Decrypted TLF client key half with any key: %+v",
			err)
	}()
	if len(keys) == 0 {
		return kbfscrypto.TLFCryptKeyClientHalf{}, -1,
			errors.WithStack(NoKeysError{})
	}
	bundles := make([]keybase1.CiphertextBundle, 0, len(keys))
	prepErrs := make([]error, 0, len(keys))
	indexLookup := make([]int, 0, len(keys))
	for i, k := range keys {
		encryptedData, nonce, prepErr :=
			c.prepareTLFCryptKeyClientHalf(k.ClientHalf)
		if err != nil {
			prepErrs = append(prepErrs, prepErr)
		} else {
			bundles = append(bundles, keybase1.CiphertextBundle{
				Kid:        k.PubKey.KID(),
				Ciphertext: encryptedData,
				Nonce:      nonce,
				PublicKey:  keybase1.BoxPublicKey(k.EPubKey.Data()),
			})
			indexLookup = append(indexLookup, i)
		}
	}
	if len(bundles) == 0 {
		return kbfscrypto.TLFCryptKeyClientHalf{}, -1, prepErrs[0]
	}
	timer := c.logAboutTooLongUnlessCancelled(ctx, "UnboxBytes32Any")
	defer timer.Stop()
	res, err := c.client.UnboxBytes32Any(ctx, keybase1.UnboxBytes32AnyArg{
		Bundles:     bundles,
		Reason:      "to rekey for kbfs",
		PromptPaper: promptPaper,
	})
	if err != nil {
		return kbfscrypto.TLFCryptKeyClientHalf{}, -1,
			errors.WithStack(err)
	}
	return kbfscrypto.MakeTLFCryptKeyClientHalf(res.Plaintext),
		indexLookup[res.Index], nil
}
580844
func MakeRandomTLFEphemeralKeys() (
	TLFEphemeralPublicKey, TLFEphemeralPrivateKey, error) {
	keyPair, err := libkb.GenerateNaclDHKeyPair()
	if err != nil {
		return TLFEphemeralPublicKey{}, TLFEphemeralPrivateKey{},
			errors.WithStack(err)
	}

	ePubKey := MakeTLFEphemeralPublicKey(keyPair.Public)
	ePrivKey := MakeTLFEphemeralPrivateKey(*keyPair.Private)
	return ePubKey, ePrivKey, nil
}
390522
func (f *FastTeamChainLoader) deriveSeedAtGeneration(m libkb.MetaContext, gen keybase1.PerTeamKeyGeneration, state *keybase1.FastTeamData) (seed keybase1.PerTeamKeySeed, err error) {

	seed, ok := state.Chain.PerTeamKeySeedsVerified[gen]
	if ok {
		return seed, nil
	}
	var tmp keybase1.PerTeamKeySeed
	tmp, ok = state.PerTeamKeySeedsUnverified[gen]
	if !ok {
		// See CORE-9207. We can hit this case if we previously loaded a parent team for verifying a subteam
		// name before we were members of the team, and then later get added to the team, and then try to
		// reload the team. We didn't have boxes from the first time around, so just force a full reload.
		// It's inefficient but it's a very rare case.
		return seed, NewFTLMissingSeedError(gen)
	}

	ptkChain, ok := state.Chain.PerTeamKeys[gen]
	if !ok {
		return seed, NewFastLoadError(fmt.Sprintf("no per team key public halves at generation %d", gen))
	}

	km, err := NewTeamKeyManagerWithSecret(tmp, gen)
	if err != nil {
		return seed, err
	}

	sigKey, err := km.SigningKey()
	if err != nil {
		return seed, err
	}

	if !ptkChain.SigKID.SecureEqual(sigKey.GetKID()) {
		m.Debug("sig KID gen:%v (local) %v != %v (chain)", gen, sigKey.GetKID(), ptkChain.SigKID)
		return seed, NewFastLoadError(fmt.Sprintf("wrong team key (sig) found at generation %v", gen))
	}

	encKey, err := km.EncryptionKey()
	if err != nil {
		return seed, err
	}

	if !ptkChain.EncKID.SecureEqual(encKey.GetKID()) {
		m.Debug("enc KID gen:%v (local) %v != %v (chain)", gen, encKey.GetKID(), ptkChain.EncKID)
		return seed, NewFastLoadError(fmt.Sprintf("wrong team key (enc) found at generation %v", gen))
	}

	// write back to cache
	seed = tmp
	state.Chain.PerTeamKeySeedsVerified[gen] = seed
	return seed, err
}
799312
func (md *RootMetadata) GetTLFCryptKeyParams(
	keyGen kbfsmd.KeyGen, user keybase1.UID, key kbfscrypto.CryptPublicKey) (
	kbfscrypto.TLFEphemeralPublicKey, kbfscrypto.EncryptedTLFCryptKeyClientHalf,
	kbfscrypto.TLFCryptKeyServerHalfID, bool, error) {
	return md.bareMd.GetTLFCryptKeyParams(keyGen, user, key, md.extra)
}
794130
func (md *RootMetadataV2) GetTLFCryptKeyParams(
	keyGen KeyGen, user keybase1.UID, key kbfscrypto.CryptPublicKey,
	_ ExtraMetadata) (
	kbfscrypto.TLFEphemeralPublicKey, kbfscrypto.EncryptedTLFCryptKeyClientHalf,
	kbfscrypto.TLFCryptKeyServerHalfID, bool, error) {
	wkb, rkb, err := md.getTLFKeyBundles(keyGen)
	if err != nil {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false, err
	}

	dkim := wkb.WKeys[user]
	if dkim == nil {
		dkim = rkb.RKeys[user]
		if dkim == nil {
			return kbfscrypto.TLFEphemeralPublicKey{},
				kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
				kbfscrypto.TLFCryptKeyServerHalfID{}, false, nil
		}
	}
	info, ok := dkim[key.KID()]
	if !ok {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false, nil
	}

	_, _, ePubKey, err := GetEphemeralPublicKeyInfoV2(info, *wkb, *rkb)
	if err != nil {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false, err
	}

	return ePubKey, info.ClientHalf, info.ServerHalfID, true, nil
}
743710
func (m *BaseShardManager) GetShardsForKeys(
	keys []string) map[int]*ShardMapping {

	m.rwMutex.RLock()
	defer m.rwMutex.RUnlock()

	numShards := len(m.shardStates)
	results := make(map[int]*ShardMapping)

	for _, key := range keys {
		shardId := m.getShardId(key, numShards)

		entry, inMap := results[shardId]
		if !inMap {
			entry = &ShardMapping{}
			if shardId != -1 {
				state := m.shardStates[shardId]
				if state.State == ActiveServer {
					m.fillEntryWithConnection(state.Address, entry)
				} else {
					connSkippedByAddr.Add(state.Address, 1)
				}
			}
			entry.Keys = make([]string, 0, 1)
			results[shardId] = entry
		}
		entry.Keys = append(entry.Keys, key)
	}

	return results
}