// MaskTLFCryptKey returns the client side of a top-level folder crypt
// key.
486140
func MaskTLFCryptKey(serverHalf TLFCryptKeyServerHalf,
	key TLFCryptKey) TLFCryptKeyClientHalf {
	return MakeTLFCryptKeyClientHalf(xorKeys(serverHalf.data, key.data))
}
1031599
func DecryptPrivateMetadata(
	encryptedPrivateMetadata EncryptedPrivateMetadata, key TLFCryptKey) (
	[]byte, error) {
	if encryptedPrivateMetadata.encryptedData.Version ==
		EncryptionSecretboxWithKeyNonce {
		// Only blocks should have v2 encryption.
		return nil, errors.WithStack(InvalidEncryptionVer{
			encryptedPrivateMetadata.encryptedData.Version})
	}

	nonce, err := encryptedPrivateMetadata.encryptedData.Nonce24()
	if err != nil {
		return nil, err
	}

	return decryptData(
		encryptedPrivateMetadata.encryptedData, key.Data(), nonce)
}
1027099
func (b KeyCacheMeasured) PutTLFCryptKey(
	tlfID tlf.ID, keyGen kbfsmd.KeyGen, key kbfscrypto.TLFCryptKey) (err error) {
	b.putTimer.Time(func() {
		err = b.delegate.PutTLFCryptKey(tlfID, keyGen, key)
	})
	return err
}
165419
func (md *RootMetadataV2) GetCurrentTLFPublicKey(
	_ ExtraMetadata) (kbfscrypto.TLFPublicKey, error) {
	if len(md.WKeys) == 0 {
		return kbfscrypto.TLFPublicKey{}, errors.New(
			"No key generations in GetCurrentTLFPublicKey")
	}
	return md.WKeys[len(md.WKeys)-1].TLFPublicKey, nil
}
123730
func (a *ActiveDevice) NaclEncryptionKey() (*NaclDHKeyPair, error) {
	genericKey, err := a.EncryptionKey()
	if err != nil {
		return nil, err
	}
	naclKey, ok := genericKey.(NaclDHKeyPair)
	if !ok {
		return nil, fmt.Errorf("expected NaclDHKeyPair, got %T", genericKey)
	}
	return &naclKey, nil
}
652017
func (c CryptoCommon) MakeRandomTLFKeys() (kbfscrypto.TLFPublicKey,
	kbfscrypto.TLFPrivateKey, kbfscrypto.TLFCryptKey, error) {
	publicKey, privateKey, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return kbfscrypto.TLFPublicKey{}, kbfscrypto.TLFPrivateKey{},
			kbfscrypto.TLFCryptKey{}, errors.WithStack(err)
	}

	pubKey := kbfscrypto.MakeTLFPublicKey(*publicKey)
	privKey := kbfscrypto.MakeTLFPrivateKey(*privateKey)

	cryptKey, err := kbfscrypto.MakeRandomTLFCryptKey()
	if err != nil {
		return kbfscrypto.TLFPublicKey{}, kbfscrypto.TLFPrivateKey{},
			kbfscrypto.TLFCryptKey{}, err
	}

	return pubKey, privKey, cryptKey, nil
}
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)
}
892217
func (c *CryptoLocal) DecryptTLFCryptKeyClientHalf(ctx context.Context,
	publicKey kbfscrypto.TLFEphemeralPublicKey,
	encryptedClientHalf kbfscrypto.EncryptedTLFCryptKeyClientHalf) (
	kbfscrypto.TLFCryptKeyClientHalf, error) {
	return kbfscrypto.DecryptTLFCryptKeyClientHalf(
		c.cryptPrivateKey, publicKey, encryptedClientHalf)
}
1096612
func (k NaclDHKeyPair) EncryptToString(plaintext []byte, sender GenericKey) (string, error) {
	var senderDh *NaclDHKeyPair
	if sender != nil {
		var ok bool
		if senderDh, ok = sender.(*NaclDHKeyPair); !ok {
			return "", NoSecretKeyError{}
		}
	}

	info, err := k.Encrypt(plaintext, senderDh)
	if err != nil {
		return "", err
	}

	return kbcrypto.EncodePacketToArmoredString(info)
}
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
}
1000914
func (x *XC) decryptPrivateKey(ctx context.Context, recp *keyring.PrivateKey) error {
	fp := recp.Fingerprint()

	for i := 0; i < maxUnlockAttempts; i++ {
		// retry asking for key in case it's wrong
		passphrase, err := x.client.Passphrase(ctx, fp, fmt.Sprintf("Unlock private key %s", recp.Fingerprint()))
		if err != nil {
			return errors.Wrapf(err, "failed to get passphrase from agent: %s", err)
		}

		if err = recp.Decrypt(passphrase); err == nil {
			// passphrase is correct, the key should now be decrypted
			return nil
		}

		// decryption failed, clear cache and wait a moment before trying again
		if err := x.client.Remove(ctx, fp); err != nil {
			return errors.Wrapf(err, "failed to clear cache")
		}
		time.Sleep(10 * time.Millisecond)
	}

	return fmt.Errorf("failed to unlock private key '%s' after %d retries", fp, maxUnlockAttempts)
}
1302566
func (s *JobData) SetEncryptionKey(v *EncryptionKey) *JobData {
	s.EncryptionKey = v
	return s
}
119155
func (p *PrivateKey) Decrypt(passphrase string) error {
	if !p.Encrypted {
		return nil
	}
	secretKey := p.deriveKey(passphrase)

	decrypted, ok := secretbox.Open(nil, p.EncryptedData, &p.Nonce, &secretKey)
	if !ok {
		return fmt.Errorf("decryption error")
	}
	copy(p.privateKey[:], decrypted)

	p.Encrypted = false
	return nil
}
370414
func (k *KeybaseServiceBase) GetTLFCryptKeys(ctx context.Context,
	query keybase1.TLFQuery) (res keybase1.GetTLFCryptKeysRes, err error) {
	if ctx, err = tlfhandle.MakeExtendedIdentify(
		CtxWithRandomIDReplayable(ctx,
			CtxKeybaseServiceIDKey, CtxKeybaseServiceOpID, k.log),
		query.IdentifyBehavior,
	); err != nil {
		return keybase1.GetTLFCryptKeysRes{}, err
	}

	tlfHandle, err := getHandleFromFolderName(
		ctx, k.config.KBPKI(), k.config.MDOps(), k.config, query.TlfName, false)
	if err != nil {
		return res, err
	}

	res.NameIDBreaks.CanonicalName = keybase1.CanonicalTlfName(
		tlfHandle.GetCanonicalName())

	keys, id, err := k.config.KBFSOps().GetTLFCryptKeys(ctx, tlfHandle)
	if err != nil {
		return res, err
	}
	res.NameIDBreaks.TlfID = keybase1.TLFID(id.String())

	for i, key := range keys {
		res.CryptKeys = append(res.CryptKeys, keybase1.CryptKey{
			KeyGeneration: int(kbfsmd.FirstValidKeyGen) + i,
			Key:           keybase1.Bytes32(key.Data()),
		})
	}

	if query.IdentifyBehavior.WarningInsteadOfErrorOnBrokenTracks() {
		res.NameIDBreaks.Breaks = tlfhandle.GetExtendedIdentify(ctx).
			GetTlfBreakAndClose()
	}

	return res, nil
}
15230
func tlsConfigKey(c *Config) (tlsCacheKey, error) {
	// Make sure ca/key/cert content is loaded
	if err := loadTLSFiles(c); err != nil {
		return tlsCacheKey{}, err
	}
	return tlsCacheKey{
		insecure:   c.TLS.Insecure,
		caData:     string(c.TLS.CAData),
		certData:   string(c.TLS.CertData),
		keyData:    string(c.TLS.KeyData),
		getCert:    fmt.Sprintf("%p", c.TLS.GetCert),
		serverName: c.TLS.ServerName,
		dial:       fmt.Sprintf("%p", c.Dial),
	}, nil
}
1021505
func (md *RootMetadataV3) GetHistoricTLFCryptKey(codec kbfscodec.Codec,
	keyGen KeyGen, currentKey kbfscrypto.TLFCryptKey, extra ExtraMetadata) (
	kbfscrypto.TLFCryptKey, error) {
	extraV3, ok := extra.(*ExtraMetadataV3)
	if !ok {
		return kbfscrypto.TLFCryptKey{}, errors.New(
			"Invalid extra metadata")
	}
	if keyGen < FirstValidKeyGen || keyGen >= md.LatestKeyGeneration() {
		return kbfscrypto.TLFCryptKey{}, errors.Errorf(
			"Invalid key generation %d", keyGen)
	}
	oldKeys, err := kbfscrypto.DecryptTLFCryptKeys(
		codec, extraV3.wkb.EncryptedHistoricTLFCryptKeys, currentKey)
	if err != nil {
		return kbfscrypto.TLFCryptKey{}, err
	}
	index := int(keyGen - FirstValidKeyGen)
	if index >= len(oldKeys) || index < 0 {
		return kbfscrypto.TLFCryptKey{}, errors.Errorf(
			"Index %d out of range (max: %d)", index, len(oldKeys))
	}
	return oldKeys[index], nil
}
1162076
func (s *TerminologyProperties) SetEncryptionKey(v *EncryptionKey) *TerminologyProperties {
	s.EncryptionKey = v
	return s
}