// ImportKeys will read the libotr formatted data given and return all accounts defined in it
174695
func ImportKeys(r io.Reader) ([]*Account, error) {
	res, ok := readAccounts(bufio.NewReader(r))
	if !ok {
		return nil, newOtrError("couldn't import data into private key")
	}
	return res, nil
}
887159
func (c *Client) GetSSHKeys() (keys []SSHKey, err error) {
	var keyMap map[string]SSHKey
	if err := c.get(`sshkey/list`, &keyMap); err != nil {
		return nil, err
	}

	for _, key := range keyMap {
		keys = append(keys, key)
	}
	sort.Sort(sshkeys(keys))
	return keys, nil
}
1073880
func loadKeys(keyFile string, keyStore KeyStore) (interface{}, interface{}, error) {
	privateKeyBytes, _, err := keyStore.LoadPrivateKey(keyFile)
	if err != nil {
		return nil, nil, err
	}
	privateKey, err := jose.LoadPrivateKey(privateKeyBytes)
	if err != nil {
		return nil, nil, err
	}

	pub, err := keyStore.LoadPublicKey(keyFile)
	if err != nil {
		return nil, nil, err
	}
	publicKey, err := jose.LoadPublicKey(pub)
	if err != nil {
		return nil, nil, err
	}
	return privateKey, publicKey, nil
}
1208502
func runSSHKeyImport(keyIds []string) map[string][]importedSSHKey {
	importResults := make(map[string][]importedSSHKey, len(keyIds))
	for _, keyId := range keyIds {
		keyInfo := []importedSSHKey{}
		output, err := RunSSHImportId(keyId)
		if err != nil {
			keyInfo = append(keyInfo, importedSSHKey{err: err})
			continue
		}
		lines := strings.Split(output, "\n")
		hasKey := false
		for _, line := range lines {
			if !strings.HasPrefix(line, "ssh-") {
				continue
			}
			hasKey = true
			// ignore key comment (e.g., user@host)
			fingerprint, _, err := ssh.KeyFingerprint(line)
			keyInfo = append(keyInfo, importedSSHKey{
				key:         line,
				fingerprint: fingerprint,
				err:         errors.Annotatef(err, "invalid ssh key for %s", keyId),
			})
		}
		if !hasKey {
			keyInfo = append(keyInfo, importedSSHKey{
				err: errors.Errorf("invalid ssh key id: %s", keyId),
			})
		}
		importResults[keyId] = keyInfo
	}
	return importResults
}
1122507
func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
	a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
	if err != nil {
		return a, err
	}
	ks.cache.add(a)
	ks.refreshWallets()
	return a, nil
}
780592
func ExportKeys(to io.Writer, s Exporter, from string) error {
	// get PEM block
	k, err := s.Get(from)
	if err != nil {
		return err
	}

	// parse PEM blocks if there are more than one
	for block, rest := pem.Decode(k); block != nil; block, rest = pem.Decode(rest) {
		// add from path in a header for later import
		block.Headers["path"] = from
		// write serialized PEM
		err = pem.Encode(to, block)
		if err != nil {
			return err
		}
	}
	return nil
}
1358696
func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
	key, err := DecryptKey(keyJSON, passphrase)
	if key != nil && key.PrivateKey != nil {
		defer zeroKey(key.PrivateKey)
	}
	if err != nil {
		return accounts.Account{}, err
	}
	return ks.importKey(key, newPassphrase)
}
217726
func (c *Client) AddKeys(user string, keys ...string) ([]params.ErrorResult, error) {
	p := params.ModifyUserSSHKeys{User: user, Keys: keys}
	results := new(params.ErrorResults)
	err := c.facade.FacadeCall("AddKeys", p, results)
	return results.Results, err
}
1127602
func (c *threadSafeMap) ListKeys() []string {
	c.lock.RLock()
	defer c.lock.RUnlock()
	list := make([]string, 0, len(c.items))
	for key := range c.items {
		list = append(list, key)
	}
	return list
}
1114683
func (pdb *BytesBrokerWatcherEtcd) ListKeys(prefix string) (keyval.BytesKeyIterator, error) {
	return listKeysInternal(pdb.Logger, pdb.kv, pdb.opTimeout, prefix)
}
267349
func ImportKeysFromFile(fname string) ([]*Account, error) {
	f, err := os.Open(fname)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return ImportKeys(f)
}
1040072
func importRootKey(cmd *cobra.Command, rootKey string, nRepo notaryclient.Repository, retriever notary.PassRetriever) ([]string, error) {
	var rootKeyList []string

	if rootKey != "" {
		privKey, err := readKey(data.CanonicalRootRole, rootKey, retriever)
		if err != nil {
			return nil, err
		}
		// add root key to repo
		err = nRepo.GetCryptoService().AddKey(data.CanonicalRootRole, "", privKey)
		if err != nil {
			return nil, fmt.Errorf("Error importing key: %v", err)
		}
		rootKeyList = []string{privKey.ID()}
	} else {
		rootKeyList = nRepo.GetCryptoService().ListKeys(data.CanonicalRootRole)
	}

	if len(rootKeyList) > 0 {
		// Chooses the first root key available, which is initialization specific
		// but should return the HW one first.
		rootKeyID := rootKeyList[0]
		cmd.Printf("Root key found, using: %s\n", rootKeyID)

		return []string{rootKeyID}, nil
	}

	return []string{}, nil
}
792017
func (cmd *ImportCommand) importValues(ctx context.Context, useColumnKeys bool, vals []pilosa.FieldValue) error {
	logger := log.New(cmd.Stderr, "", log.LstdFlags)

	// If keys are used, all values are sent to the primary translate store (i.e. coordinator).
	if useColumnKeys {
		logger.Printf("importing keyed values: n=%d", len(vals))
		if err := cmd.client.ImportValueK(ctx, cmd.Index, cmd.Field, vals); err != nil {
			return errors.Wrap(err, "importing keys")
		}
		return nil
	}

	// Group vals by shard.
	logger.Printf("grouping %d vals", len(vals))
	valsByShard := http.FieldValues(vals).GroupByShard()

	// Parse path into FieldValues.
	for shard, vals := range valsByShard {
		if cmd.Sort {
			sort.Sort(http.FieldValues(vals))
		}

		logger.Printf("importing shard: %d, n=%d", shard, len(vals))
		if err := cmd.client.ImportValue(ctx, cmd.Index, cmd.Field, shard, vals, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil {
			return errors.Wrap(err, "importing values")
		}
	}

	return nil
}
493337
func FilterKeys(authorizer acl.Authorizer, keys []string) []string {
	kf := keyFilter{authorizer: authorizer, keys: keys}
	return keys[:FilterEntries(&kf)]
}
304353
func importPerUserKeyBox(box *keybase1.PerUserKeyBox, decryptionKey GenericKey,
	wantedGeneration keybase1.PerUserKeyGeneration, checker *perUserKeyChecker) (*importedPerUserKey, error) {
	if box == nil {
		return nil, NewPerUserKeyImportError("per-user-key box nil")
	}
	if box.Generation != wantedGeneration {
		return nil, NewPerUserKeyImportError("bad generation returned: %d", box.Generation)
	}
	if !decryptionKey.GetKID().Equal(box.ReceiverKID) {
		return nil, NewPerUserKeyImportError("wrong encryption kid: %s", box.ReceiverKID.String())
	}
	rawKey, encryptingKID, err := decryptionKey.DecryptFromString(box.Box)
	if err != nil {
		return nil, err
	}
	if len(checker.allowedEncryptingKIDs) == 0 {
		return nil, NewPerUserKeyImportError("no allowed encrypting kids")
	}
	if !checker.allowedEncryptingKIDs[encryptingKID] {
		return nil, NewPerUserKeyImportError("unexpected encrypting kid: %s", encryptingKID)
	}
	seed, err := MakeByte32Soft(rawKey)
	if err != nil {
		return nil, NewPerUserKeyImportError("%s", err)
	}
	imp, err := expandPerUserKey(seed)
	if err != nil {
		return nil, NewPerUserKeyImportError("%s", err)
	}
	err = checker.checkPublic(imp, wantedGeneration)
	if err != nil {
		return nil, err
	}
	return &imp, nil
}
1135769
func (api *API) Import(ctx context.Context, req *ImportRequest, opts ...ImportOption) error {
	span, _ := tracing.StartSpanFromContext(ctx, "API.Import")
	defer span.Finish()

	if err := api.validate(apiImport); err != nil {
		return errors.Wrap(err, "validating api method")
	}

	// Set up import options.
	options, err := setUpImportOptions(opts...)
	if err != nil {
		return errors.Wrap(err, "setting up import options")
	}

	index, field, err := api.indexField(req.Index, req.Field, req.Shard)
	if err != nil {
		return errors.Wrap(err, "getting index and field")
	}

	// Unless explicitly ignoring key validation (meaning keys have been
	// translated to ids in a previous step at the coordinator node), then
	// check to see if keys need translation.
	if !options.IgnoreKeyCheck {
		// Translate row keys.
		if field.keys() {
			if len(req.RowIDs) != 0 {
				return errors.New("row ids cannot be used because field uses string keys")
			}
			if req.RowIDs, err = api.holder.translateFile.TranslateRowsToUint64(index.Name(), field.Name(), req.RowKeys); err != nil {
				return errors.Wrap(err, "translating rows")
			}
		}

		// Translate column keys.
		if index.Keys() {
			if len(req.ColumnIDs) != 0 {
				return errors.New("column ids cannot be used because index uses string keys")
			}
			if req.ColumnIDs, err = api.holder.translateFile.TranslateColumnsToUint64(index.Name(), req.ColumnKeys); err != nil {
				return errors.Wrap(err, "translating columns")
			}
		}

		// For translated data, map the columnIDs to shards. If
		// this node does not own the shard, forward to the node that does.
		if index.Keys() || field.keys() {
			m := make(map[uint64][]Bit)

			for i, colID := range req.ColumnIDs {
				shard := colID / ShardWidth
				if _, ok := m[shard]; !ok {
					m[shard] = make([]Bit, 0)
				}
				m[shard] = append(m[shard], Bit{
					RowID:     req.RowIDs[i],
					ColumnID:  colID,
					Timestamp: req.Timestamps[i],
				})
			}

			// Signal to the receiving nodes to ignore checking for key translation.
			opts = append(opts, OptImportOptionsIgnoreKeyCheck(true))

			var eg errgroup.Group
			for shard, bits := range m {
				// TODO: if local node owns this shard we don't need to go through the client
				shard := shard
				bits := bits
				eg.Go(func() error {
					return api.server.defaultClient.Import(ctx, req.Index, req.Field, shard, bits, opts...)
				})
			}
			return eg.Wait()
		}
	}

	// Validate shard ownership.
	if err := api.validateShardOwnership(req.Index, req.Shard); err != nil {
		return errors.Wrap(err, "validating shard ownership")
	}

	// Convert timestamps to time.Time.
	timestamps := make([]*time.Time, len(req.Timestamps))
	for i, ts := range req.Timestamps {
		if ts == 0 {
			continue
		}
		t := time.Unix(0, ts).UTC()
		timestamps[i] = &t
	}

	// Import columnIDs into existence field.
	if !options.Clear {
		if err := importExistenceColumns(index, req.ColumnIDs); err != nil {
			api.server.logger.Printf("import existence error: index=%s, field=%s, shard=%d, columns=%d, err=%s", req.Index, req.Field, req.Shard, len(req.ColumnIDs), err)
			return errors.Wrap(err, "importing existence columns")
		}
	}

	// Import into fragment.
	err = field.Import(req.RowIDs, req.ColumnIDs, timestamps, opts...)
	if err != nil {
		api.server.logger.Printf("import error: index=%s, field=%s, shard=%d, columns=%d, err=%s", req.Index, req.Field, req.Shard, len(req.ColumnIDs), err)
	}
	return errors.Wrap(err, "importing")
}
788209
func loadKeys(keyFile string, keyStore KeyStore) (jose.Encrypter, interface{}, error) {
	privateKey, _, err := keyStore.LoadPrivateKey(keyFile)
	if err != nil {
		return nil, nil, err
	}
	decryptionKey, err := jose.LoadPrivateKey(privateKey)
	if err != nil {
		return nil, nil, err
	}

	pub, err := keyStore.LoadPublicKey(keyFile)
	if err != nil {
		return nil, nil, err
	}
	publicKey, err := jose.LoadPublicKey(pub)
	if err != nil {
		return nil, nil, err
	}

	encrypter, err := jose.NewEncrypter(keyAlgorithm, contentEncryption, publicKey)
	if err != nil {
		return nil, nil, err
	}

	return encrypter, decryptionKey, err
}