// StoreKey generates a key, encrypts with 'auth' and stores in the given directory
339668
func StoreKey(dir, auth string, scryptN, scryptP int) (common.Address, error) {
	_, a, err := storeNewKey(&keyStorePassphrase{dir, scryptN, scryptP, false}, rand.Reader, auth)
	return a.Address, err
}
757294
func (r *RootKeyStorage) RootKey(_ context.Context) ([]byte, []byte, error) {
	if r.encKey == nil {
		return nil, nil, ErrStoreLocked
	}
	var rootKey []byte
	id := defaultRootKeyID
	err := r.Update(func(tx *bbolt.Tx) error {
		ns := tx.Bucket(rootKeyBucketName)
		dbKey := ns.Get(id)

		// If there's a root key stored in the bucket, decrypt it and
		// return it.
		if len(dbKey) != 0 {
			decKey, err := r.encKey.Decrypt(dbKey)
			if err != nil {
				return err
			}

			rootKey = make([]byte, len(decKey))
			copy(rootKey[:], decKey[:])
			return nil
		}

		// Otherwise, create a RootKeyLen-byte root key, encrypt it,
		// and store it in the bucket.
		rootKey = make([]byte, RootKeyLen)
		if _, err := io.ReadFull(rand.Reader, rootKey[:]); err != nil {
			return err
		}

		encKey, err := r.encKey.Encrypt(rootKey)
		if err != nil {
			return err
		}
		return ns.Put(id, encKey)
	})
	if err != nil {
		return nil, nil, err
	}

	return rootKey, id, nil
}
734877
func (s *GenericKeyStore) RemoveKey(keyID string) error {
	s.Lock()
	defer s.Unlock()
	delete(s.cachedKeys, keyID)

	err := s.store.Remove(keyID)
	if err != nil {
		return err
	}

	delete(s.keyInfoMap, keyID)
	return nil
}
1187531
func (a *API) Store(ctx context.Context, data io.Reader, size int64, toEncrypt bool) (addr storage.Address, wait func(ctx context.Context) error, err error) {
	log.Debug("api.store", "size", size)
	return a.fileStore.Store(ctx, data, size, toEncrypt)
}
126838
func (a *LocalKeyAgent) GetKey() (*Key, error) {
	return a.keyStore.GetKey(a.proxyHost, a.username)
}
71310
func (db *gcsTokenDB) StoreToken(user string, v *TokenDBValue, updatePassword bool) (dp string, err error) {
	if updatePassword {
		dp = uniuri.New()
		dph, _ := bcrypt.GenerateFromPassword([]byte(dp), bcrypt.DefaultCost)
		v.DockerPassword = string(dph)
	}

	wr := db.gcs.Bucket(db.bucket).Object(user).NewWriter(context.Background())

	if err := json.NewEncoder(wr).Encode(v); err != nil {
		glog.Errorf("failed to set token data for %s: %s", user, err)
		return "", fmt.Errorf("failed to set token data for %s due: %v", user, err)
	}

	err = wr.Close()
	return
}
1194045
func (t *TeamKeyManager) EncryptionKey() (libkb.NaclDHKeyPair, error) {
	if t.encryptionKey == nil {
		key, err := libkb.MakeNaclDHKeyPairFromSecretBytes(derivedSecret(t.sharedSecret, libkb.TeamDHDerivationString))
		if err != nil {
			return libkb.NaclDHKeyPair{}, err
		}
		t.encryptionKey = &key
	}
	return *t.encryptionKey, nil
}
721280
func (m *Manager) cachedKey(filename string) (*ecdsa.PrivateKey, error) {
	keyfile := filepath.Join(m.CacheDir, filename)

	// try to load cached credentials
	store, err := pemutil.LoadFile(keyfile)
	if err != nil && os.IsNotExist(err) {
		store, err = pemutil.GenerateECKeySet(elliptic.P256())
		if err != nil {
			return nil, fmt.Errorf("could not generate ec key set: %v", err)
		}
		err = os.MkdirAll(m.CacheDir, 0700)
		if err != nil {
			return nil, fmt.Errorf("could not create cache directory: %v", err)
		}
		err = store.WriteFile(keyfile)
		if err != nil {
			return nil, fmt.Errorf("could not save PEM: %v", err)
		}
	} else if err != nil {
		return nil, fmt.Errorf("unexpected error: %v", err)
	}

	// grab key
	key, ok := store.ECPrivateKey()
	if !ok {
		return nil, fmt.Errorf("%s does not contain ec private key", keyfile)
	}

	return key, nil
}
415880
func (s Store) ECPrivateKey() (*ecdsa.PrivateKey, bool) {
	v, ok := s[ECPrivateKey]
	if !ok {
		return nil, false
	}
	z, ok := v.(*ecdsa.PrivateKey)
	return z, ok
}
149877
func (g *Goon) Key(src interface{}) *datastore.Key {
	if k, err := g.KeyError(src); err == nil {
		return k
	}
	return nil
}
1077186
func (fkvs *FileKeyValueStore) Store(key interface{}, value interface{}) error {
	if key == nil {
		return errors.New("key is nil")
	}
	if value == nil {
		return errors.New("value is nil")
	}
	file, err := fkvs.keySerializer(key)
	if err != nil {
		return err
	}
	valueBytes, err := fkvs.marshaller(value)
	if err != nil {
		return err
	}
	err = os.MkdirAll(filepath.Dir(file), newDirMode)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(file, valueBytes, newFileMode)
}
1292288
func (d *autoSeal) SetStoredKeys(ctx context.Context, keys [][]byte) error {
	if keys == nil {
		return fmt.Errorf("keys were nil")
	}
	if len(keys) == 0 {
		return fmt.Errorf("no keys provided")
	}

	buf, err := json.Marshal(keys)
	if err != nil {
		return errwrap.Wrapf("failed to encode keys for storage: {{err}}", err)
	}

	// Encrypt and marshal the keys
	blobInfo, err := d.Encrypt(ctx, buf)
	if err != nil {
		return errwrap.Wrapf("failed to encrypt keys for storage: {{err}}", err)
	}

	value, err := proto.Marshal(blobInfo)
	if err != nil {
		return errwrap.Wrapf("failed to marshal value for storage: {{err}}", err)
	}

	// Store the seal configuration.
	pe := &physical.Entry{
		Key:   StoredBarrierKeysPath,
		Value: value,
	}

	if err := d.core.physical.Put(ctx, pe); err != nil {
		return errwrap.Wrapf("failed to write keys to storage: {{err}}", err)
	}

	return nil
}
185747
func PackageKey(c context.Context, pkg string) *datastore.Key {
	return datastore.NewKey(c, "Package", pkg, 0, nil)
}
87227
func (c *nativeStore) Store(authConfig types.AuthConfig) error {
	if err := c.storeCredentialsInStore(authConfig); err != nil {
		return err
	}
	authConfig.Username = ""
	authConfig.Password = ""
	authConfig.IdentityToken = ""

	// Fallback to old credential in plain text to save only the email
	return c.fileStore.Store(authConfig)
}
884584
func NewCryptoStore(s Store, encryptionCipher string, encryptionKey []byte) (*CryptoStore, error) {
	code, mkh, err := createMasterKeyHash(encryptionCipher, encryptionKey)
	if err != nil {
		return nil, err
	}
	cs := &CryptoStore{
		Store: s,
		code:  code,
		mkh:   mkh,
	}
	// On success, erase the key
	for i := 0; i < len(encryptionKey); i++ {
		encryptionKey[i] = 'x'
	}
	return cs, nil
}
1258302
func PwStoreDir(mount string) string {
	if mount != "" {
		return fsutil.CleanPath(filepath.Join(Homedir(), ".password-store-"+strings.Replace(mount, string(filepath.Separator), "-", -1)))
	}
	if d := os.Getenv("PASSWORD_STORE_DIR"); d != "" {
		return fsutil.CleanPath(d)
	}
	return filepath.Join(Homedir(), ".password-store")
}
230196
func (s *GenericKeyStore) AddKey(keyInfo KeyInfo, privKey data.PrivateKey) error {
	var (
		chosenPassphrase string
		giveup           bool
		err              error
		pemPrivKey       []byte
	)
	s.Lock()
	defer s.Unlock()
	if keyInfo.Role == data.CanonicalRootRole || data.IsDelegation(keyInfo.Role) || !data.ValidRole(keyInfo.Role) {
		keyInfo.Gun = ""
	}
	keyID := privKey.ID()
	for attempts := 0; ; attempts++ {
		chosenPassphrase, giveup, err = s.PassRetriever(keyID, keyInfo.Role.String(), true, attempts)
		if err == nil {
			break
		}
		if giveup || attempts > 10 {
			return ErrAttemptsExceeded{}
		}
	}

	pemPrivKey, err = utils.ConvertPrivateKeyToPKCS8(privKey, keyInfo.Role, keyInfo.Gun, chosenPassphrase)

	if err != nil {
		return err
	}

	s.cachedKeys[keyID] = &cachedKey{role: keyInfo.Role, key: privKey}
	err = s.store.Set(keyID, pemPrivKey)
	if err != nil {
		return err
	}
	s.keyInfoMap[privKey.ID()] = keyInfo
	return nil
}