// DeserializeTLFReaderKeyBundleV3 deserializes a TLFReaderKeyBundleV3
// from the given path and returns it.
344308
func DeserializeTLFReaderKeyBundleV3(codec kbfscodec.Codec, path string) (
	TLFReaderKeyBundleV3, error) {
	var rkb TLFReaderKeyBundleV3
	err := kbfscodec.DeserializeFromFile(codec, path, &rkb)
	if err != nil {
		return TLFReaderKeyBundleV3{}, err
	}
	if len(rkb.Keys) == 0 {
		rkb.Keys = make(UserDeviceKeyInfoMapV3)
	}
	return rkb, nil
}
336583
func (wkg TLFWriterKeyGenerationsV2) ToTLFWriterKeyBundleV3(
	codec kbfscodec.Codec,
	tlfCryptKeyGetter func() ([]kbfscrypto.TLFCryptKey, error)) (
	TLFWriterKeyBundleV2, TLFWriterKeyBundleV3, error) {
	keyGen := wkg.LatestKeyGeneration()
	if keyGen < FirstValidKeyGen {
		return TLFWriterKeyBundleV2{}, TLFWriterKeyBundleV3{},
			errors.New("No key generations to convert")
	}

	// Copy the latest UserDeviceKeyInfoMap.
	wkbV2 := wkg[keyGen-FirstValidKeyGen]
	ePubKeyCount := len(wkbV2.TLFEphemeralPublicKeys)
	udkimV3, err := writerUDKIMV2ToV3(codec, wkbV2.WKeys, ePubKeyCount)
	if err != nil {
		return TLFWriterKeyBundleV2{}, TLFWriterKeyBundleV3{}, err
	}
	wkbV3 := TLFWriterKeyBundleV3{
		Keys: udkimV3,
		TLFEphemeralPublicKeys: make(
			kbfscrypto.TLFEphemeralPublicKeys, ePubKeyCount),
		TLFPublicKey: wkbV2.TLFPublicKey,
	}
	// Copy all of the TLFEphemeralPublicKeys at this generation.
	copy(wkbV3.TLFEphemeralPublicKeys[:], wkbV2.TLFEphemeralPublicKeys)

	if keyGen > FirstValidKeyGen {
		// Fetch all of the TLFCryptKeys.
		keys, err := tlfCryptKeyGetter()
		if err != nil {
			return TLFWriterKeyBundleV2{}, TLFWriterKeyBundleV3{}, err
		}
		// Sanity check.
		if len(keys) != int(keyGen) {
			return TLFWriterKeyBundleV2{}, TLFWriterKeyBundleV3{},
				fmt.Errorf("expected %d keys, found %d", keyGen, len(keys))
		}
		// Save the current key.
		currKey := keys[len(keys)-1]
		// Get rid of the most current generation as that's in the UserDeviceKeyInfoMap already.
		keys = keys[:len(keys)-1]
		// Encrypt the historic keys with the current key.
		wkbV3.EncryptedHistoricTLFCryptKeys, err = kbfscrypto.EncryptTLFCryptKeys(codec, keys, currKey)
		if err != nil {
			return TLFWriterKeyBundleV2{}, TLFWriterKeyBundleV3{}, err
		}
	}

	return wkbV2, wkbV3, nil
}
748672
func TLSDataFromFiles(caPath, certPath, keyPath string) (*TLSData, error) {
	var (
		ca, cert, key []byte
		err           error
	)
	if caPath != "" {
		if ca, err = ioutil.ReadFile(caPath); err != nil {
			return nil, err
		}
	}
	if certPath != "" {
		if cert, err = ioutil.ReadFile(certPath); err != nil {
			return nil, err
		}
	}
	if keyPath != "" {
		if key, err = ioutil.ReadFile(keyPath); err != nil {
			return nil, err
		}
	}
	if ca == nil && cert == nil && key == nil {
		return nil, nil
	}
	return &TLSData{CA: ca, Cert: cert, Key: key}, nil
}
1274227
func (c *CryptoClient) DecryptTLFCryptKeyClientHalf(ctx context.Context,
	publicKey kbfscrypto.TLFEphemeralPublicKey,
	encryptedClientHalf kbfscrypto.EncryptedTLFCryptKeyClientHalf) (
	clientHalf kbfscrypto.TLFCryptKeyClientHalf, err error) {
	c.log.CDebugf(ctx, "Decrypting TLF client key half")
	defer func() {
		c.deferLog.CDebugf(ctx, "Decrypted TLF client key half: %+v",
			err)
	}()
	encryptedData, nonce, err := c.prepareTLFCryptKeyClientHalf(
		encryptedClientHalf)
	if err != nil {
		return kbfscrypto.TLFCryptKeyClientHalf{}, err
	}

	timer := c.logAboutTooLongUnlessCancelled(ctx, "UnboxBytes32")
	defer timer.Stop()
	decryptedClientHalf, err := c.client.UnboxBytes32(ctx, keybase1.UnboxBytes32Arg{
		EncryptedBytes32: encryptedData,
		Nonce:            nonce,
		PeersPublicKey:   keybase1.BoxPublicKey(publicKey.Data()),
		Reason:           "to use kbfs",
	})
	if err != nil {
		return kbfscrypto.TLFCryptKeyClientHalf{}, errors.WithStack(err)
	}

	return kbfscrypto.MakeTLFCryptKeyClientHalf(decryptedClientHalf), nil
}
17297
func (rkb TLFReaderKeyBundleV3) Size() (bytes int) {
	bytes += cache.PtrSize + rkb.Keys.Size() // Keys

	// TLFEphemeralPublicKeys
	bytes += rkb.TLFEphemeralPublicKeys.Size()

	// For codec.UnknownFieldSetHandler. It has a private map field which we
	// can't inspect unless extending the codec package. Just assume it's empty
	// for now.
	bytes += cache.PtrSize

	return bytes
}
187944
func (k *KeyBundleCacheStandard) PutTLFReaderKeyBundle(
	bundleID TLFReaderKeyBundleID, rkb TLFReaderKeyBundleV3) {
	k.cache.Add(bundleID, rkb)
}
213212
func (km *KeyManagerStandard) GetTLFCryptKeyForMDDecryption(
	ctx context.Context, kmdToDecrypt, kmdWithKeys libkey.KeyMetadata) (
	tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
	return km.getTLFCryptKey(ctx, kmdWithKeys, kmdToDecrypt.LatestKeyGeneration(),
		getTLFCryptKeyAnyDevice|getTLFCryptKeyDoCache)
}
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)
}
1110642
func (k *KeyCacheStandard) PutTLFCryptKey(
	tlf tlf.ID, keyGen kbfsmd.KeyGen, key kbfscrypto.TLFCryptKey) error {
	cacheKey := keyCacheKey{tlf, keyGen}
	k.lru.Add(cacheKey, key)
	return nil
}
17641
func (cr *s3ChunkedReader) readS3ChunkHeader() {
	// Read the first chunk line until CRLF.
	var hexChunkSize, hexChunkSignature []byte
	hexChunkSize, hexChunkSignature, cr.err = readChunkLine(cr.reader)
	if cr.err != nil {
		return
	}
	// <hex>;token=value - converts the hex into its uint64 form.
	cr.n, cr.err = parseHexUint(hexChunkSize)
	if cr.err != nil {
		return
	}
	if cr.n == 0 {
		cr.err = io.EOF
	}
	// Save the incoming chunk signature.
	cr.chunkSignature = string(hexChunkSignature)
}
741286
func (c *CryptoLocal) DecryptTLFCryptKeyClientHalfAny(ctx context.Context,
	keys []EncryptedTLFCryptKeyClientAndEphemeral, _ bool) (
	clientHalf kbfscrypto.TLFCryptKeyClientHalf, index int, err error) {
	if len(keys) == 0 {
		return kbfscrypto.TLFCryptKeyClientHalf{}, -1,
			errors.WithStack(NoKeysError{})
	}
	var firstNonDecryptionErr error
	for i, k := range keys {
		clientHalf, err := c.DecryptTLFCryptKeyClientHalf(
			ctx, k.EPubKey, k.ClientHalf)
		if err != nil {
			_, isDecryptionError :=
				errors.Cause(err).(libkb.DecryptionError)
			if firstNonDecryptionErr == nil && !isDecryptionError {
				firstNonDecryptionErr = err
			}
			continue
		}
		return clientHalf, i, nil
	}
	// This is to mimic the behavior in
	// CryptoClient.DecryptTLFCryptKeyClientHalfAny, which is to,
	// if all calls to prepareTLFCryptKeyClientHalf failed, return
	// the first prep error, and otherwise to return the error
	// from the service, which is usually libkb.DecryptionError.
	if firstNonDecryptionErr != nil {
		return kbfscrypto.TLFCryptKeyClientHalf{}, -1,
			firstNonDecryptionErr
	}
	return kbfscrypto.TLFCryptKeyClientHalf{}, -1,
		errors.WithStack(libkb.DecryptionError{})
}
911410
func (b KeyBundleCacheMeasured) GetTLFReaderKeyBundle(
	bundleID kbfsmd.TLFReaderKeyBundleID) (rkb *kbfsmd.TLFReaderKeyBundleV3, err error) {
	b.attemptReaderBundleCountMeter.Mark(1)
	b.getReaderBundleTimer.Time(func() {
		rkb, err = b.delegate.GetTLFReaderKeyBundle(bundleID)
	})
	if err == nil && rkb != nil {
		b.hitReaderBundleCountMeter.Mark(1)
	}
	return rkb, err
}
1084494
func TLFReaderKeyBundleIDFromString(id string) (TLFReaderKeyBundleID, error) {
	if len(id) == 0 {
		return TLFReaderKeyBundleID{}, nil
	}
	h, err := kbfshash.HashFromString(id)
	if err != nil {
		return TLFReaderKeyBundleID{}, err
	}
	return TLFReaderKeyBundleID{h}, nil
}
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
}
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
}
866160
func (md *RootMetadataV3) UpdateKeyBundles(codec kbfscodec.Codec,
	extra ExtraMetadata,
	updatedWriterKeys, updatedReaderKeys UserDevicePublicKeys,
	ePubKey kbfscrypto.TLFEphemeralPublicKey,
	ePrivKey kbfscrypto.TLFEphemeralPrivateKey,
	tlfCryptKeys []kbfscrypto.TLFCryptKey) (
	[]UserDeviceKeyServerHalves, error) {
	if len(tlfCryptKeys) != 1 {
		return nil, fmt.Errorf(
			"(MDv3) Expected 1 TLF crypt key, got %d",
			len(tlfCryptKeys))
	}

	serverHalves, err := md.updateKeyBundles(codec, extra,
		updatedWriterKeys, updatedReaderKeys,
		ePubKey, ePrivKey, tlfCryptKeys[0])
	if err != nil {
		return nil, err
	}

	return []UserDeviceKeyServerHalves{serverHalves}, nil
}
1169233
func (md *MDServerRemote) DeleteTLFCryptKeyServerHalf(ctx context.Context,
	uid keybase1.UID, key kbfscrypto.CryptPublicKey,
	serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) (err error) {
	ctx = rpc.WithFireNow(ctx)
	md.log.LazyTrace(ctx, "KeyServer: DeleteTLFCryptKeyServerHalf %s %s", uid, serverHalfID)
	defer func() {
		md.deferLog.LazyTrace(ctx, "KeyServer: DeleteTLFCryptKeyServerHalf %s %s done (err=%v)", uid, serverHalfID, err)
	}()

	// encode the ID
	idBytes, err := md.config.Codec().Encode(serverHalfID)
	if err != nil {
		return err
	}

	// get the key
	arg := keybase1.DeleteKeyArg{
		Uid:       uid,
		DeviceKID: key.KID(),
		KeyHalfID: idBytes,
		LogTags:   nil,
	}
	err = md.getClient().DeleteKey(ctx, arg)
	if err != nil {
		return err
	}

	return nil
}