// ViewAndRotateKEK re-encrypts the key with a new KEK
964240
func (k *KeyReadWriter) ViewAndRotateKEK(cb func(KEKData, PEMKeyHeaders) (KEKData, PEMKeyHeaders, error)) error {
	k.mu.Lock()
	defer k.mu.Unlock()

	updatedKEK, updatedHeaderObj, err := cb(k.kekData, k.headersObj)
	if err != nil {
		return err
	}

	keyBlock, err := k.readKey()
	if err != nil {
		return err
	}

	return k.writeKey(keyBlock, updatedKEK, updatedHeaderObj)
}
214967
func (c *cipherState) Encrypt(associatedData, cipherText, plainText []byte) []byte {
	defer func() {
		c.nonce++

		if c.nonce == keyRotationInterval {
			c.rotateKey()
		}
	}()

	var nonce [12]byte
	binary.LittleEndian.PutUint64(nonce[4:], c.nonce)

	return c.cipher.Seal(cipherText, nonce[:], plainText, associatedData)
}
1358208
func (p *NullPKI) KeyAndClaims(pkey []byte) (interface{}, []string, error) {
	return jwt.UnsafeAllowNoneSignatureType, []string{}, nil
}
145476
func (this *LRUCache) GetAndUnCompress(key interface{}) (value []byte, compressor Compressor, ok bool) {
	this.locker.RLock()
	defer this.locker.RUnlock()

	valInter, ok := this.Cache.Get(lru.Key(key))
	if !ok {
		return
	}

	if compressor, ok = valInter.(Compressor); ok {
		var err error
		value, err = compressor.UnCompress()
		if err != nil {
			ok = false
			return
		}
	}

	return
}
935945
func Convert_security_PodSecurityPolicyReview_To_v1_PodSecurityPolicyReview(in *security.PodSecurityPolicyReview, out *v1.PodSecurityPolicyReview, s conversion.Scope) error {
	return autoConvert_security_PodSecurityPolicyReview_To_v1_PodSecurityPolicyReview(in, out, s)
}
59013
func (md *RootMetadata) fakeInitialRekey() {
	bh, err := md.tlfHandle.ToBareHandle()
	if err != nil {
		panic(err)
	}
	md.extra = kbfsmd.FakeInitialRekey(md.bareMd, bh, kbfscrypto.TLFPublicKey{})
}
1360712
func (r *RaftDEKManager) MaybeUpdateKEK(candidateKEK ca.KEKData) (bool, bool, error) {
	var updated, unlockedToLocked bool
	err := r.kw.ViewAndRotateKEK(func(currentKEK ca.KEKData, h ca.PEMKeyHeaders) (ca.KEKData, ca.PEMKeyHeaders, error) {
		var err error
		updated, unlockedToLocked, err = compareKEKs(currentKEK, candidateKEK)
		if err == nil && !updated { // if we don't need to rotate the KEK, don't bother updating
			err = errNoUpdateNeeded
		}
		if err != nil {
			return ca.KEKData{}, nil, err
		}

		data, ok := h.(RaftDEKData)
		if !ok {
			return ca.KEKData{}, nil, errNotUsingRaftDEKData
		}

		if unlockedToLocked {
			data.NeedsRotation = true
		}
		return candidateKEK, data, nil
	})
	if err == errNoUpdateNeeded {
		err = nil
	}

	if err == nil && unlockedToLocked {
		r.rotationCh <- struct{}{}
	}
	return updated, unlockedToLocked, err
}
1026414
func (c CryptoCommon) EncryptPrivateMetadata(
	pmd PrivateMetadata, key kbfscrypto.TLFCryptKey) (
	encryptedPmd kbfscrypto.EncryptedPrivateMetadata, err error) {
	encodedPmd, err := c.codec.Encode(pmd)
	if err != nil {
		return kbfscrypto.EncryptedPrivateMetadata{}, err
	}

	return kbfscrypto.EncryptEncodedPrivateMetadata(encodedPmd, key)
}
1265606
func (b *AESGCMBarrier) Rotate(ctx context.Context) (uint32, error) {
	b.l.Lock()
	defer b.l.Unlock()
	if b.sealed {
		return 0, ErrBarrierSealed
	}

	// Generate a new key
	encrypt, err := b.GenerateKey()
	if err != nil {
		return 0, errwrap.Wrapf("failed to generate encryption key: {{err}}", err)
	}

	// Get the next term
	term := b.keyring.ActiveTerm()
	newTerm := term + 1

	// Add a new encryption key
	newKeyring, err := b.keyring.AddKey(&Key{
		Term:    newTerm,
		Version: 1,
		Value:   encrypt,
	})
	if err != nil {
		return 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err)
	}

	// Persist the new keyring
	if err := b.persistKeyring(ctx, newKeyring); err != nil {
		return 0, err
	}

	// Swap the keyrings
	b.keyring = newKeyring
	return newTerm, nil
}
1106347
func (s *MemoryStore) View(cb func(ReadTx)) {
	defer metrics.StartTimer(viewLatencyTimer)()
	memDBTx := s.memDB.Txn(false)

	readTx := readTx{
		memDBTx: memDBTx,
	}
	cb(readTx)
	memDBTx.Commit()
}
65744
func (s *APNSVoipSandboxChannelResponse) SetHasTokenKey(v bool) *APNSVoipSandboxChannelResponse {
	s.HasTokenKey = &v
	return s
}
220198
func (met *Metrics) FetchAndReset(keys ...string) map[string]int64 {
	state := make(map[string]int64)

	met.storeGuard.Lock()
	for _, key := range keys {
		if val, exists := met.store[key]; exists {
			state[key] = *val
			*val = 0
		}
	}
	met.storeGuard.Unlock()

	met.rateGuard.Lock()
	for _, key := range keys {
		if rate, exists := met.rates[key]; exists {
			rate.lastSample = 0
			rate.value = 0
			rate.index = 0
			rate.samples.Set(0)
		}
	}
	met.rateGuard.Unlock()

	return state
}
1185532
func RotateSnapshotKey(gun data.GUN, store storage.MetaStore, crypto signed.CryptoService, createAlgorithm string) (data.PublicKey, error) {
	// Always attempt to create a new key, but this might be rate-limited
	key, err := crypto.Create(data.CanonicalSnapshotRole, gun, createAlgorithm)
	if err != nil {
		return nil, err
	}
	logrus.Debug("Created new pending snapshot key ", key.ID(), "to rotate to for ", gun, ". With algo: ", key.Algorithm())
	return key, nil
}
849705
func defaultRotationStrategy(rotationFrequency, idTokenValidFor time.Duration) rotationStrategy {
	return rotationStrategy{
		rotationFrequency: rotationFrequency,
		idTokenValidFor:   idTokenValidFor,
		key: func() (*rsa.PrivateKey, error) {
			return rsa.GenerateKey(rand.Reader, 2048)
		},
	}
}
1158891
func (c *PassphraseChange) findAndDecryptPrivatePGPKeys(m libkb.MetaContext) ([]libkb.GenericKey, error) {

	var keyList []libkb.GenericKey

	// Using a paper key makes TripleSec-synced keys unrecoverable
	if c.usingPaper {
		m.Debug("using a paper key, thus TripleSec-synced keys are unrecoverable")
		return keyList, nil
	}

	// Only use the synced secret keys:
	blocks, err := c.me.AllSyncedSecretKeys(m)
	if err != nil {
		return nil, err
	}

	secretRetriever := libkb.NewSecretStore(c.G(), c.me.GetNormalizedName())

	for _, block := range blocks {
		parg := m.SecretKeyPromptArg(libkb.SecretKeyArg{}, "passphrase change")
		key, err := block.PromptAndUnlock(m, parg, secretRetriever, c.me)
		if err != nil {
			return nil, err
		}
		keyList = append(keyList, key)
	}

	return keyList, nil
}
397920
func staticRotationStrategy(key *rsa.PrivateKey) rotationStrategy {
	return rotationStrategy{
		// Setting these values to 100 years is easier than having a flag indicating no rotation.
		rotationFrequency: time.Hour * 8760 * 100,
		idTokenValidFor:   time.Hour * 8760 * 100,
		key:               func() (*rsa.PrivateKey, error) { return key, nil },
	}
}
1025980
func parseKV(kv *mvccpb.KeyValue) *event {
	return &event{
		key:       string(kv.Key),
		value:     kv.Value,
		prevValue: nil,
		rev:       kv.ModRevision,
		isDeleted: false,
		isCreated: true,
	}
}