// Ensure -key.pem exists, and has correct size and key type
542065
func (c *Cert) EnsureKey() error {
	if err := c.ensureDestination(); err != nil {
		return fmt.Errorf("error ensuring destination: %v", err)
	}

	path := c.Destination() + "-key.pem"
	_, err := os.Stat(path)

	// Path doesn't exist
	if err != nil && os.IsNotExist(err) {
		c.Log.Debug("Pem file doesn't exist")
		c.Log.Infof("Key doesn't exist at path: %s", path)
		if err := c.genAndWriteKey(path); err != nil {
			return err
		}
		return c.WritePermissions(path, os.FileMode(0600))
	}

	//Path Exists
	c.Log.Debug("Pem file exists '-key.pem'")
	if err := c.loadKeyFromFile(path); err != nil {
		return fmt.Errorf("failed to load rsa key from file '%s': %v", path, err)
	}

	if c.KeyType() != c.Data().Type {
		c.Log.Warnf("key doesn't match expected type at path '%s'. exp=%s got=%s", path, c.KeyType(), c.Data().Type)
		// Wrong key type
		// Delete File, Generate new and write to file
		if err := c.DeleteFile(path); err != nil {
			return err
		}
		return c.genAndWriteKey(path)
	}
	if c.BitSize() != c.PemSize() {
		c.Log.Infof("key doesn't match expected size at path '%s'. exp=%d got=%d", path, c.BitSize(), c.PemSize())
		//Wrong bit size
		// Delete file, generate new and write to file
		if err := c.DeleteFile(path); err != nil {
			return err
		}
		return c.genAndWriteKey(path)
	}

	return c.WritePermissions(path, os.FileMode(0600))
}
722077
func ParsePublicKeyPEM(bytes []byte) (interface{}, error) {
	block, _ := pem.Decode(bytes)
	if block == nil {
		return nil, trace.BadParameter("expected PEM-encoded block")
	}
	return ParsePublicKeyDER(block.Bytes)
}
1354063
func EnsureKVMs(c context.Context, cfgs []*config.Datacenter, platformIds, rackIds map[string]int64) (map[string]int64, error) {
	t := &KVMsTable{}
	t.platforms = platformIds
	t.racks = rackIds
	if err := t.fetch(c); err != nil {
		return nil, errors.Annotate(err, "failed to fetch KVMs").Err()
	}
	if err := t.computeChanges(c, cfgs); err != nil {
		return nil, errors.Annotate(err, "failed to compute changes").Err()
	}
	if err := t.add(c); err != nil {
		return nil, errors.Annotate(err, "failed to add KVMs").Err()
	}
	if err := t.remove(c); err != nil {
		return nil, errors.Annotate(err, "failed to remove KVMs").Err()
	}
	if err := t.update(c); err != nil {
		return nil, errors.Annotate(err, "failed to update KVMs").Err()
	}
	return t.ids(c), nil
}
1013819
func (srv *Config) Ensure(c context.Context, req *config.EnsureRequest) (*config.Config, error) {
	srv.cfg.Store(req.GetId(), req.GetConfig())
	return req.GetConfig(), nil
}
1159330
func (s *Server) processTrustedKeys() bool {
	if trustedKeys != "" && !s.initStampedTrustedKeys() {
		return false
	} else if s.opts.TrustedKeys != nil {
		for _, key := range s.opts.TrustedKeys {
			if !nkeys.IsValidPublicOperatorKey(key) {
				return false
			}
		}
		s.trustedKeys = s.opts.TrustedKeys
	}
	return true
}
881126
func Verify(publicKey *[PublicKeySize]byte, message []byte, sig *[SignatureSize]byte) bool {
	if sig[63]&224 != 0 {
		return false
	}

	var A edwards25519.ExtendedGroupElement
	if !A.FromBytes(publicKey) {
		return false
	}
	edwards25519.FeNeg(&A.X, &A.X)
	edwards25519.FeNeg(&A.T, &A.T)

	h := sha512.New()
	h.Write(sig[:32])
	h.Write(publicKey[:])
	h.Write(message)
	var digest [64]byte
	h.Sum(digest[:0])

	var hReduced [32]byte
	edwards25519.ScReduce(&hReduced, &digest)

	var R edwards25519.ProjectiveGroupElement
	var b [32]byte
	copy(b[:], sig[32:])
	edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b)

	var checkR [32]byte
	R.ToBytes(&checkR)
	return subtle.ConstantTimeCompare(sig[:32], checkR[:]) == 1
}
533703
func (u *utils) ParsePrivateKeyPEMWithPassword(pemBytes, password []byte) (crypto.Signer, error) {
	block, _ := pem.Decode(pemBytes)
	if block == nil {
		return nil, errors.New("Could not parse PEM")
	}

	if IsPKCS8(block.Bytes) {
		return pkcs8.ParsePrivateKeyPEMWithPassword(pemBytes, password)
	} else if u.fips {
		return nil, ErrFIPSUnsupportedKeyFormat
	}

	return helpers.ParsePrivateKeyPEMWithPassword(pemBytes, password)
}
1180906
func ValidateKey(key string) error {
	if len(key) <= keyMaxLength && keyRegex.MatchString(key) {
		return nil
	}
	return fmt.Errorf("invalid key: %q", key)
}
838249
func (u *user) checkKey(kid keybase1.KID) error {
	var err error
	if _, ok := u.sibkeys[kid]; !ok {
		if _, ok := u.subkeys[kid]; !ok {
			err = BadKeyError{u.uid, kid}
		}
	}
	return err
}
889950
func (instance *LazyPublicKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) {
	err := instance.loadIfRequired()
	if err != nil {
		return nil, err
	}
	if err := AssertPublicKeyAndTokenCombination(instance.publicKey, token); err != nil {
		return nil, err
	}
	return instance.publicKey, nil
}
1211002
func IsKeyEExistsError(err error) bool {

	res, ok := err.(*gomemcached.MCResponse)
	if ok && res.Status == gomemcached.KEY_EEXISTS {
		return true
	}

	return false
}
385881
func EnsureEd25519PrivateKeyCorrect(candidatePrivateKey ed25519.PrivateKey) error {
	if len(candidatePrivateKey) != ed25519.PrivateKeySize {
		return fmt.Errorf("ed25519 key has size %v but %v bytes passed as key", ed25519.PrivateKeySize,
			len(candidatePrivateKey))
	}
	_, derivedPrivateKey, err := ed25519.GenerateKey(bytes.NewBuffer(candidatePrivateKey))
	if err != nil {
		return err
	}
	if !bytes.Equal(derivedPrivateKey, candidatePrivateKey) {
		return fmt.Errorf("ed25519 key generated from prefix of %X should equal %X, but is %X",
			candidatePrivateKey, candidatePrivateKey, derivedPrivateKey)
	}
	return nil
}
268359
func (m *SigningMethodRSA) Verify(raw []byte, sig Signature, key interface{}) error {
	rsaKey, ok := key.(*rsa.PublicKey)
	if !ok {
		return ErrInvalidKey
	}
	return rsa.VerifyPKCS1v15(rsaKey, m.Hash, m.sum(raw), sig)
}
311109
func (r *PEXReactor) ensurePeers() {
	var (
		out, in, dial = r.Switch.NumPeers()
		numToDial     = r.Switch.MaxNumOutboundPeers() - (out + dial)
	)
	r.Logger.Info(
		"Ensure peers",
		"numOutPeers", out,
		"numInPeers", in,
		"numDialing", dial,
		"numToDial", numToDial,
	)

	if numToDial <= 0 {
		return
	}

	// bias to prefer more vetted peers when we have fewer connections.
	// not perfect, but somewhate ensures that we prioritize connecting to more-vetted
	// NOTE: range here is [10, 90]. Too high ?
	newBias := cmn.MinInt(out, 8)*10 + 10

	toDial := make(map[p2p.ID]*p2p.NetAddress)
	// Try maxAttempts times to pick numToDial addresses to dial
	maxAttempts := numToDial * 3

	for i := 0; i < maxAttempts && len(toDial) < numToDial; i++ {
		try := r.book.PickAddress(newBias)
		if try == nil {
			continue
		}
		if _, selected := toDial[try.ID]; selected {
			continue
		}
		if r.Switch.IsDialingOrExistingAddress(try) {
			continue
		}
		// TODO: consider moving some checks from toDial into here
		// so we don't even consider dialing peers that we want to wait
		// before dialling again, or have dialed too many times already
		r.Logger.Info("Will dial address", "addr", try)
		toDial[try.ID] = try
	}

	// Dial picked addresses
	for _, addr := range toDial {
		go r.dialPeer(addr)
	}

	// If we need more addresses, pick a random peer and ask for more.
	if r.book.NeedMoreAddrs() {
		peers := r.Switch.Peers().List()
		peersCount := len(peers)
		if peersCount > 0 {
			peer := peers[cmn.RandInt()%peersCount] // nolint: gas
			r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
			r.RequestAddrs(peer)
		}
	}

	// If we are not connected to nor dialing anybody, fallback to dialing a seed.
	if out+in+dial+len(toDial) == 0 {
		r.Logger.Info("No addresses to dial nor connected peers. Falling back to seeds")
		r.dialSeeds()
	}
}
422544
func (ks *Keystore) TrustedKeyPrefixExists(prefix string) (bool, error) {
	acidentifier, err := types.NewACIdentifier(prefix)
	if err != nil {
		return false, err
	}

	pathNamesPrefix := []string{
		// example: /etc/rkt/trustedkeys/prefix.d/coreos.com/etcd
		path.Join(ks.LocalPrefixPath, acidentifier.String()),
		// example: /usr/lib/rkt/trustedkeys/prefix.d/coreos.com/etcd
		path.Join(ks.SystemPrefixPath, acidentifier.String()),
	}

	for _, p := range pathNamesPrefix {
		_, err := os.Stat(p)
		if os.IsNotExist(err) {
			continue
		}
		if err != nil {
			return false, errwrap.Wrap(fmt.Errorf("cannot check dir %q", p), err)
		}
		files, err := ioutil.ReadDir(p)
		if err != nil {
			return false, errwrap.Wrap(fmt.Errorf("cannot list files in dir %q", p), err)
		}
		for _, f := range files {
			if !f.IsDir() && f.Size() > 0 {
				return true, nil
			}
		}
	}

	parentPrefix, _ := path.Split(prefix)
	parentPrefix = strings.Trim(parentPrefix, "/")

	if parentPrefix != "" {
		return ks.TrustedKeyPrefixExists(parentPrefix)
	}

	return false, nil
}
142464
func (v RSAPSSVerifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
	// will return err if keytype is not a recognized RSA type
	pubKey, err := getRSAPubKey(key)
	if err != nil {
		return err
	}

	digest := sha256.Sum256(msg)

	return verifyPSS(pubKey, digest[:], sig)
}
1301079
func (k *kubernetesClient) EnsureOperator(appName, agentPath string, config *caas.OperatorConfig) error {
	logger.Debugf("creating/updating %s operator", appName)

	operatorName := k.operatorName(appName)
	// TODO(caas) use secrets for storing agent password?
	if config.AgentConf == nil {
		// We expect that the config map already exists,
		// so make sure it does.
		configMaps := k.client().CoreV1().ConfigMaps(k.namespace)
		_, err := configMaps.Get(operatorConfigMapName(operatorName), v1.GetOptions{IncludeUninitialized: true})
		if err != nil {
			return errors.Annotatef(err, "config map for %q should already exist", appName)
		}
	} else {
		if err := k.ensureConfigMap(operatorConfigMap(appName, operatorName, config)); err != nil {
			return errors.Annotate(err, "creating or updating ConfigMap")
		}
	}

	annotations := resourceTagsToAnnotations(config.ResourceTags).
		Add(labelVersion, config.Version.String())

	// Set up the parameters for creating charm storage.
	operatorVolumeClaim := "charm"
	if isLegacyName(operatorName) {
		operatorVolumeClaim = fmt.Sprintf("%v-operator-volume", appName)
	}

	fsSize, err := resource.ParseQuantity(fmt.Sprintf("%dMi", config.CharmStorage.Size))
	if err != nil {
		return errors.Annotatef(err, "invalid volume size %v", config.CharmStorage.Size)
	}
	params := volumeParams{
		storageConfig:       &storageConfig{},
		pvcName:             operatorVolumeClaim,
		requestedVolumeSize: fsSize,
	}
	if config.CharmStorage.Provider != K8s_ProviderType {
		return errors.Errorf("expected charm storage provider %q, got %q", K8s_ProviderType, config.CharmStorage.Provider)
	}
	params.storageConfig, err = newStorageConfig(config.CharmStorage.Attributes)
	if err != nil {
		return errors.Annotatef(err, "invalid storage configuration for %v operator", appName)
	}
	// We want operator storage to be deleted when the operator goes away.
	params.storageConfig.reclaimPolicy = core.PersistentVolumeReclaimDelete
	logger.Debugf("operator storage config %#v", *params.storageConfig)

	// Attempt to get a persistent volume to store charm state etc.
	pvcSpec, err := k.maybeGetVolumeClaimSpec(params)
	if err != nil {
		return errors.Annotate(err, "finding operator volume claim")
	}

	pvc := &core.PersistentVolumeClaim{
		ObjectMeta: v1.ObjectMeta{
			Name:        params.pvcName,
			Annotations: resourceTagsToAnnotations(config.CharmStorage.ResourceTags).ToMap()},
		Spec: *pvcSpec,
	}
	pod, err := operatorPod(
		operatorName,
		appName,
		agentPath,
		config.OperatorImagePath,
		config.Version.String(),
		annotations.Copy(),
	)
	if err != nil {
		return errors.Annotate(err, "generating operator podspec")
	}
	// Take a copy for use with statefulset.
	podWithoutStorage := pod

	numPods := int32(1)
	logger.Debugf("using persistent volume claim for operator %s: %+v", appName, pvc)
	statefulset := &apps.StatefulSet{
		ObjectMeta: v1.ObjectMeta{
			Name:        operatorName,
			Labels:      map[string]string{labelOperator: appName},
			Annotations: annotations.ToMap()},
		Spec: apps.StatefulSetSpec{
			Replicas: &numPods,
			Selector: &v1.LabelSelector{
				MatchLabels: map[string]string{labelOperator: appName},
			},
			Template: core.PodTemplateSpec{
				ObjectMeta: v1.ObjectMeta{
					Labels:      map[string]string{labelOperator: appName},
					Annotations: pod.Annotations,
				},
			},
			PodManagementPolicy:  apps.ParallelPodManagement,
			VolumeClaimTemplates: []core.PersistentVolumeClaim{*pvc},
		},
	}
	pod.Spec.Containers[0].VolumeMounts = append(pod.Spec.Containers[0].VolumeMounts, core.VolumeMount{
		Name:      pvc.Name,
		MountPath: agent.BaseDir(agentPath),
	})

	statefulset.Spec.Template.Spec = pod.Spec
	err = k.ensureStatefulSet(statefulset, podWithoutStorage.Spec)
	return errors.Annotatef(err, "creating or updating %v operator StatefulSet", appName)
}