// PutTLFReaderKeyBundle implements the KeyBundleCache interface for KeyBundleCacheStandard.
187944
func (k *KeyBundleCacheStandard) PutTLFReaderKeyBundle(
	bundleID TLFReaderKeyBundleID, rkb TLFReaderKeyBundleV3) {
	k.cache.Add(bundleID, rkb)
}
307128
func (cg *CertGeneratorHandler) SetBundler(caBundleFile, intBundleFile string) (err error) {
	cg.bundler, err = bundler.NewBundler(caBundleFile, intBundleFile)
	return err
}
671086
func (md *RootMetadataV2) UpdateKeyBundles(codec kbfscodec.Codec,
	_ ExtraMetadata,
	updatedWriterKeys, updatedReaderKeys UserDevicePublicKeys,
	ePubKey kbfscrypto.TLFEphemeralPublicKey,
	ePrivKey kbfscrypto.TLFEphemeralPrivateKey,
	tlfCryptKeys []kbfscrypto.TLFCryptKey) (
	[]UserDeviceKeyServerHalves, error) {
	if md.TlfID().Type() != tlf.Private {
		return nil, InvalidNonPrivateTLFOperation{
			md.TlfID(), "UpdateKeyBundles", md.Version()}
	}

	expectedTLFCryptKeyCount := int(
		md.LatestKeyGeneration() - FirstValidKeyGen + 1)
	if len(tlfCryptKeys) != expectedTLFCryptKeyCount {
		return nil, fmt.Errorf(
			"(MDv2) Expected %d TLF crypt keys, got %d",
			expectedTLFCryptKeyCount, len(tlfCryptKeys))
	}

	serverHalves := make([]UserDeviceKeyServerHalves, len(tlfCryptKeys))
	if len(updatedWriterKeys) == 0 {
		// Reader rekey case.

		for keyGen := FirstValidKeyGen; keyGen <= md.LatestKeyGeneration(); keyGen++ {
			serverHalvesGen, err :=
				md.updateKeyGenerationForReaderRekey(codec,
					keyGen, updatedReaderKeys,
					ePubKey, ePrivKey,
					tlfCryptKeys[keyGen-FirstValidKeyGen])
			if err != nil {
				return nil, err
			}

			serverHalves[keyGen-FirstValidKeyGen] = serverHalvesGen
		}

		return serverHalves, nil
	}

	// Usual rekey case.

	for keyGen := FirstValidKeyGen; keyGen <= md.LatestKeyGeneration(); keyGen++ {
		serverHalvesGen, err := md.updateKeyGeneration(
			keyGen, updatedWriterKeys, updatedReaderKeys,
			ePubKey, ePrivKey,
			tlfCryptKeys[keyGen-FirstValidKeyGen])
		if err != nil {
			return nil, err
		}

		serverHalves[keyGen-FirstValidKeyGen] = serverHalvesGen
	}
	return serverHalves, nil

}
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
}
728690
func ParseBundle(data []byte, sender net.Addr) (Bundle, error) {
	return parseBundle(data, sender, -1)
}
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
}
203557
func (s *InstanceSnapshot) SetFromBundleId(v string) *InstanceSnapshot {
	s.FromBundleId = &v
	return s
}
855066
func (c *CertBundle) ToParsedCertBundle() (*ParsedCertBundle, error) {
	result := &ParsedCertBundle{}
	var err error
	var pemBlock *pem.Block

	if len(c.PrivateKey) > 0 {
		pemBlock, _ = pem.Decode([]byte(c.PrivateKey))
		if pemBlock == nil {
			return nil, errutil.UserError{Err: "Error decoding private key from cert bundle"}
		}

		result.PrivateKeyBytes = pemBlock.Bytes
		result.PrivateKeyFormat = BlockType(strings.TrimSpace(pemBlock.Type))

		switch result.PrivateKeyFormat {
		case ECBlock:
			result.PrivateKeyType, c.PrivateKeyType = ECPrivateKey, ECPrivateKey
		case PKCS1Block:
			c.PrivateKeyType, result.PrivateKeyType = RSAPrivateKey, RSAPrivateKey
		case PKCS8Block:
			t, err := getPKCS8Type(pemBlock.Bytes)
			if err != nil {
				return nil, errutil.UserError{Err: fmt.Sprintf("Error getting key type from pkcs#8: %v", err)}
			}
			result.PrivateKeyType = t
			switch t {
			case ECPrivateKey:
				c.PrivateKeyType = ECPrivateKey
			case RSAPrivateKey:
				c.PrivateKeyType = RSAPrivateKey
			}
		default:
			return nil, errutil.UserError{Err: fmt.Sprintf("Unsupported key block type: %s", pemBlock.Type)}
		}

		result.PrivateKey, err = result.getSigner()
		if err != nil {
			return nil, errutil.UserError{Err: fmt.Sprintf("Error getting signer: %s", err)}
		}
	}

	if len(c.Certificate) > 0 {
		pemBlock, _ = pem.Decode([]byte(c.Certificate))
		if pemBlock == nil {
			return nil, errutil.UserError{Err: "Error decoding certificate from cert bundle"}
		}
		result.CertificateBytes = pemBlock.Bytes
		result.Certificate, err = x509.ParseCertificate(result.CertificateBytes)
		if err != nil {
			return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle: %v", err)}
		}
	}
	switch {
	case len(c.CAChain) > 0:
		for _, cert := range c.CAChain {
			pemBlock, _ := pem.Decode([]byte(cert))
			if pemBlock == nil {
				return nil, errutil.UserError{Err: "Error decoding certificate from cert bundle"}
			}

			parsedCert, err := x509.ParseCertificate(pemBlock.Bytes)
			if err != nil {
				return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle via CA chain: %v", err)}
			}

			certBlock := &CertBlock{
				Bytes:       pemBlock.Bytes,
				Certificate: parsedCert,
			}
			result.CAChain = append(result.CAChain, certBlock)
		}

	// For backwards compatibility
	case len(c.IssuingCA) > 0:
		pemBlock, _ = pem.Decode([]byte(c.IssuingCA))
		if pemBlock == nil {
			return nil, errutil.UserError{Err: "Error decoding ca certificate from cert bundle"}
		}

		parsedCert, err := x509.ParseCertificate(pemBlock.Bytes)
		if err != nil {
			return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle via issuing CA: %v", err)}
		}

		certBlock := &CertBlock{
			Bytes:       pemBlock.Bytes,
			Certificate: parsedCert,
		}
		result.CAChain = append(result.CAChain, certBlock)
	}

	// Populate if it isn't there already
	if len(c.SerialNumber) == 0 && len(c.Certificate) > 0 {
		c.SerialNumber = GetHexFormatted(result.Certificate.SerialNumber.Bytes(), ":")
	}

	return result, nil
}
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
}
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)
}
1087773
func NewKeyBundleCacheMeasured(delegate kbfsmd.KeyBundleCache, r metrics.Registry) KeyBundleCacheMeasured {
	getReaderBundleTimer := metrics.GetOrRegisterTimer("KeyBundleCache.GetTLFReaderKeyBundle", r)
	putReaderBundleTimer := metrics.GetOrRegisterTimer("KeyBundleCache.PutTLFReaderKeyBundle", r)
	getWriterBundleTimer := metrics.GetOrRegisterTimer("KeyBundleCache.GetTLFWriterKeyBundle", r)
	putWriterBundleTimer := metrics.GetOrRegisterTimer("KeyBundleCache.PutTLFWriterKeyBundle", r)
	hitReaderBundleCountMeter := metrics.GetOrRegisterMeter("KeyBundleCache.TLFReaderKeyBundleHitCount", r)
	hitWriterBundleCountMeter := metrics.GetOrRegisterMeter("KeyBundleCache.TLFWriterKeyBundleHitCount", r)
	attemptReaderBundleCountMeter := metrics.GetOrRegisterMeter("KeyBundleCache.TLFReaderKeyBundleAttemptCount", r)
	attemptWriterBundleCountMeter := metrics.GetOrRegisterMeter("KeyBundleCache.TLFWriterKeyBundleAttemptCount", r)
	return KeyBundleCacheMeasured{
		delegate:                      delegate,
		getReaderBundleTimer:          getReaderBundleTimer,
		getWriterBundleTimer:          getWriterBundleTimer,
		putReaderBundleTimer:          putReaderBundleTimer,
		putWriterBundleTimer:          putWriterBundleTimer,
		hitReaderBundleCountMeter:     hitReaderBundleCountMeter,
		hitWriterBundleCountMeter:     hitWriterBundleCountMeter,
		attemptReaderBundleCountMeter: attemptReaderBundleCountMeter,
		attemptWriterBundleCountMeter: attemptWriterBundleCountMeter,
	}
}
415669
func (pc *PublicCertificates) CertificateForKey(key string) (*x509.Certificate, error) {
	// Use fast reader lock first.
	pc.lock.RLock()
	cert, ok := pc.cache[key]
	pc.lock.RUnlock()
	if ok {
		return cert, nil
	}

	// Grab the write lock and recheck the cache.
	pc.lock.Lock()
	defer pc.lock.Unlock()
	if cert, ok := pc.cache[key]; ok {
		return cert, nil
	}

	for _, cert := range pc.Certificates {
		if cert.KeyName == key {
			block, _ := pem.Decode([]byte(cert.X509CertificatePEM))
			if block == nil {
				return nil, fmt.Errorf("signature: the certificate %q is not PEM encoded", key)
			}
			cert, err := x509.ParseCertificate(block.Bytes)
			if err != nil {
				return nil, err
			}
			if pc.cache == nil {
				pc.cache = make(map[string]*x509.Certificate)
			}
			pc.cache[key] = cert
			return cert, nil
		}
	}

	return nil, fmt.Errorf("signature: no such certificate %q", key)
}
725469
func CertBundleToKey(leafCert *x509.Certificate, intCerts []*x509.Certificate) (data.PublicKey, error) {
	certBundle := []*x509.Certificate{leafCert}
	certBundle = append(certBundle, intCerts...)
	certChainPEM, err := CertChainToPEM(certBundle)
	if err != nil {
		return nil, err
	}
	var newKey data.PublicKey
	// Use the leaf cert's public key algorithm for typing
	switch leafCert.PublicKeyAlgorithm {
	case x509.RSA:
		newKey = data.NewRSAx509PublicKey(certChainPEM)
	case x509.ECDSA:
		newKey = data.NewECDSAx509PublicKey(certChainPEM)
	default:
		logrus.Debugf("Unknown key type parsed from certificate: %v", leafCert.PublicKeyAlgorithm)
		return nil, x509.ErrUnsupportedAlgorithm
	}
	return newKey, nil
}
116656
func serializeKeysetBundle(o *kops.Keyset) ([]byte, error) {
	var objectData bytes.Buffer
	codecs := kopscodecs.Codecs
	yaml, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), "application/yaml")
	if !ok {
		glog.Fatalf("no YAML serializer registered")
	}
	encoder := codecs.EncoderForVersion(yaml.Serializer, v1alpha2.SchemeGroupVersion)

	if err := encoder.Encode(o, &objectData); err != nil {
		return nil, fmt.Errorf("error serializing keyset: %v", err)
	}
	return objectData.Bytes(), nil
}
672015
func (dbcr *DiskBlockCacheRemote) Put(ctx context.Context, tlfID tlf.ID,
	blockID kbfsblock.ID, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	_ DiskBlockCacheType) (err error) {
	dbcr.log.LazyTrace(ctx, "DiskBlockCacheRemote: Put %s", blockID)
	defer func() {
		dbcr.log.LazyTrace(ctx, "DiskBlockCacheRemote: Put %s done (err=%+v)", blockID, err)
	}()

	return dbcr.client.PutBlock(ctx, kbgitkbfs.PutBlockArg{
		TlfID:      tlfID.Bytes(),
		BlockID:    blockID.Bytes(),
		Buf:        buf,
		ServerHalf: serverHalf.Bytes(),
	})
}
850180
func (c *VFSCAStore) loadKeysetBundle(p vfs.Path) (*keyset, error) {
	data, err := p.ReadFile()
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		} else {
			return nil, fmt.Errorf("unable to read bundle %q: %v", p, err)
		}
	}

	o, format, err := c.parseKeysetYaml(data)
	if err != nil {
		return nil, fmt.Errorf("error parsing bundle %q: %v", p, err)
	}

	keyset, err := parseKeyset(o)
	if err != nil {
		return nil, fmt.Errorf("error mapping bundle %q: %v", p, err)
	}

	keyset.format = format
	return keyset, nil
}
156981
func PutCertificate(d Depot, name string, crt *pkix.Certificate) error {
	b, err := crt.Export()
	if err != nil {
		return err
	}
	return d.Put(CrtTag(name), b)
}