// fetchPrivKey attempts to retrieve the raw private key corresponding to the
// passed public key if populated, or the key descriptor path (if non-empty).
558357
func (b *BtcWallet) fetchPrivKey(keyDesc *keychain.KeyDescriptor) (*btcec.PrivateKey, error) {
	// If the key locator within the descriptor *isn't* empty, then we can
	// directly derive the keys raw.
	if !keyDesc.KeyLocator.IsEmpty() {
		// We'll assume the special lightning key scope in this case.
		scopedMgr, err := b.wallet.Manager.FetchScopedKeyManager(
			b.chainKeyScope,
		)
		if err != nil {
			return nil, err
		}

		var key *btcec.PrivateKey
		err = walletdb.View(b.db, func(tx walletdb.ReadTx) error {
			addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)

			path := waddrmgr.DerivationPath{
				Account: uint32(keyDesc.Family),
				Branch:  0,
				Index:   uint32(keyDesc.Index),
			}
			addr, err := scopedMgr.DeriveFromKeyPath(addrmgrNs, path)
			if err != nil {
				return err
			}

			key, err = addr.(waddrmgr.ManagedPubKeyAddress).PrivKey()
			return err
		})
		if err != nil {
			return nil, err
		}

		return key, nil
	}

	hash160 := btcutil.Hash160(keyDesc.PubKey.SerializeCompressed())
	addr, err := btcutil.NewAddressWitnessPubKeyHash(hash160, b.netParams)
	if err != nil {
		return nil, err
	}

	return b.wallet.PrivKeyForAddress(addr)
}
1258257
func (s *GenericKeyStore) GetKey(keyID string) (data.PrivateKey, data.RoleName, error) {
	s.Lock()
	defer s.Unlock()

	cachedKeyEntry, ok := s.cachedKeys[keyID]
	if ok {
		return cachedKeyEntry.key, cachedKeyEntry.role, nil
	}

	role, err := getKeyRole(s.store, keyID)
	if err != nil {
		return nil, "", err
	}

	keyBytes, err := s.store.Get(keyID)
	if err != nil {
		return nil, "", err
	}

	// See if the key is encrypted. If its encrypted we'll fail to parse the private key
	privKey, err := utils.ParsePEMPrivateKey(keyBytes, "")
	if err != nil {
		privKey, _, err = GetPasswdDecryptBytes(s.PassRetriever, keyBytes, keyID, string(role))
		if err != nil {
			return nil, "", err
		}
	}
	s.cachedKeys[keyID] = &cachedKey{role: role, key: privKey}
	return privKey, role, nil
}
266603
func (c *Client) ImportPrivKeyRescan(privKeyWIF *btcutil.WIF, label string, rescan bool) error {
	return c.ImportPrivKeyRescanAsync(privKeyWIF, label, rescan).Receive()
}
1294324
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
	key.Precompute()

	version := 0
	if len(key.Primes) > 2 {
		version = 1
	}

	priv := pkcs1PrivateKey{
		Version: version,
		N:       key.N,
		E:       key.PublicKey.E,
		D:       key.D,
		P:       key.Primes[0],
		Q:       key.Primes[1],
		Dp:      key.Precomputed.Dp,
		Dq:      key.Precomputed.Dq,
		Qinv:    key.Precomputed.Qinv,
	}

	priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
	for i, values := range key.Precomputed.CRTValues {
		priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
		priv.AdditionalPrimes[i].Exp = values.Exp
		priv.AdditionalPrimes[i].Coeff = values.Coeff
	}

	b, _ := asn1.Marshal(priv)
	return b
}
646302
func GeneratePrivateKey() (crypto.Signer, string, error) {
	pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, "", fmt.Errorf("error generating private key: %s", err)
	}

	bs, err := x509.MarshalECPrivateKey(pk)
	if err != nil {
		return nil, "", fmt.Errorf("error generating private key: %s", err)
	}

	var buf bytes.Buffer
	err = pem.Encode(&buf, &pem.Block{Type: "EC PRIVATE KEY", Bytes: bs})
	if err != nil {
		return nil, "", fmt.Errorf("error encoding private key: %s", err)
	}

	return pk, buf.String(), nil
}
1325719
func GetPrivateKey(d Depot, name string) (key *pkix.Key, err error) {
	b, err := d.Get(PrivKeyTag(name))
	if err != nil {
		return nil, err
	}
	return pkix.NewKeyFromPrivateKeyPEM(b)
}
499042
func MarshalPrivateKey(k PrivKey) ([]byte, error) {

	switch k.(type) {
	case *Ed25519PrivateKey:
		return k.Bytes()
	case *RsaPrivateKey:
		return k.Bytes()
	case *Secp256k1PrivateKey:
		return k.Bytes()
	default:
		return nil, ErrBadKeyType
	}
}
1328539
func (c *ClientConn) loadPrivateKey(typ, data string) (err error) {
	requestMap := &map[string]interface{}{}

	var k = keyPayload{
		Typ:  typ,
		Data: data,
	}

	if err = ConvertToGeneral(k, requestMap); err != nil {
		return fmt.Errorf("error creating request: %v", err)
	}

	msg, err := c.Request("load-key", *requestMap)
	if msg["success"] != "yes" {
		return fmt.Errorf("unsuccessful loadPrivateKey: %v", msg["success"])
	}

	return nil
}
686219
func (c *ClientConn) LoadRSAPrivateKey(key *rsa.PrivateKey) error {
	var mk = x509.MarshalPKCS1PrivateKey(key)

	var pemData = pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: mk,
	})

	return c.loadPrivateKey("RSA", string(pemData))
}
1015851
func (client *SSHClient) GetSSHPrivateKey() string {
	client.Creds.mu.Lock()
	defer client.Creds.mu.Unlock()
	return client.Creds.SSHPrivateKey
}
266154
func (tx *transaction) fetchKey(key []byte) []byte {
	// When the transaction is writable, check the pending transaction
	// state first.
	if tx.writable {
		if tx.pendingRemove.Has(key) {
			return nil
		}
		if value := tx.pendingKeys.Get(key); value != nil {
			return value
		}
	}

	// Consult the database cache and underlying database.
	return tx.snapshot.Get(key)
}
1297423
func (n *IpfsNode) GetKey(name string) (ic.PrivKey, error) {
	if name == "self" {
		if n.PrivateKey == nil {
			return nil, fmt.Errorf("private key not available")
		}
		return n.PrivateKey, nil
	} else {
		return n.Repo.Keystore().Get(name)
	}
}
412502
func (key *Key) PublicKey() *Key {
	keyBytes := key.Key

	if key.IsPrivate {
		keyBytes = publicKeyForPrivateKey(keyBytes)
	}

	return &Key{
		Version:     PublicWalletVersion,
		Key:         keyBytes,
		Depth:       key.Depth,
		ChildNumber: key.ChildNumber,
		FingerPrint: key.FingerPrint,
		ChainCode:   key.ChainCode,
		IsPrivate:   false,
	}
}
1361668
func TryLoadPrivatePublicKeyFromDisk(pkiPath, name string) (*rsa.PrivateKey, *rsa.PublicKey, error) {
	privateKeyPath := pathForKey(pkiPath, name)

	// Parse the private key from a file
	privKey, err := keyutil.PrivateKeyFromFile(privateKeyPath)
	if err != nil {
		return nil, nil, errors.Wrapf(err, "couldn't load the private key file %s", privateKeyPath)
	}

	publicKeyPath := pathForPublicKey(pkiPath, name)

	// Parse the public key from a file
	pubKeys, err := keyutil.PublicKeysFromFile(publicKeyPath)
	if err != nil {
		return nil, nil, errors.Wrapf(err, "couldn't load the public key file %s", publicKeyPath)
	}

	// Allow RSA format only
	k, ok := privKey.(*rsa.PrivateKey)
	if !ok {
		return nil, nil, errors.Errorf("the private key file %s isn't in RSA format", privateKeyPath)
	}

	p := pubKeys[0].(*rsa.PublicKey)

	return k, p, nil
}
1109139
func chainedPrivKey(privkey, pubkey, chaincode []byte) ([]byte, error) {
	if len(privkey) != 32 {
		return nil, fmt.Errorf("invalid privkey length %d (must be 32)",
			len(privkey))
	}
	if len(chaincode) != 32 {
		return nil, fmt.Errorf("invalid chaincode length %d (must be 32)",
			len(chaincode))
	}
	switch n := len(pubkey); n {
	case btcec.PubKeyBytesLenUncompressed, btcec.PubKeyBytesLenCompressed:
		// Correct length
	default:
		return nil, fmt.Errorf("invalid pubkey length %d", n)
	}

	xorbytes := make([]byte, 32)
	chainMod := chainhash.DoubleHashB(pubkey)
	for i := range xorbytes {
		xorbytes[i] = chainMod[i] ^ chaincode[i]
	}
	chainXor := new(big.Int).SetBytes(xorbytes)
	privint := new(big.Int).SetBytes(privkey)

	t := new(big.Int).Mul(chainXor, privint)
	b := t.Mod(t, btcec.S256().N).Bytes()
	return pad(32, b), nil
}
1000914
func (x *XC) decryptPrivateKey(ctx context.Context, recp *keyring.PrivateKey) error {
	fp := recp.Fingerprint()

	for i := 0; i < maxUnlockAttempts; i++ {
		// retry asking for key in case it's wrong
		passphrase, err := x.client.Passphrase(ctx, fp, fmt.Sprintf("Unlock private key %s", recp.Fingerprint()))
		if err != nil {
			return errors.Wrapf(err, "failed to get passphrase from agent: %s", err)
		}

		if err = recp.Decrypt(passphrase); err == nil {
			// passphrase is correct, the key should now be decrypted
			return nil
		}

		// decryption failed, clear cache and wait a moment before trying again
		if err := x.client.Remove(ctx, fp); err != nil {
			return errors.Wrapf(err, "failed to clear cache")
		}
		time.Sleep(10 * time.Millisecond)
	}

	return fmt.Errorf("failed to unlock private key '%s' after %d retries", fp, maxUnlockAttempts)
}
407662
func fetchCoinTypeKeys(ns walletdb.ReadBucket, scope *KeyScope) ([]byte, []byte, error) {
	scopedBucket, err := fetchReadScopeBucket(ns, scope)
	if err != nil {
		return nil, nil, err
	}

	coinTypePubKeyEnc := scopedBucket.Get(coinTypePubKeyName)
	if coinTypePubKeyEnc == nil {
		str := "required encrypted cointype public key not stored in database"
		return nil, nil, managerError(ErrDatabase, str, nil)
	}

	coinTypePrivKeyEnc := scopedBucket.Get(coinTypePrivKeyName)
	if coinTypePrivKeyEnc == nil {
		str := "required encrypted cointype private key not stored in database"
		return nil, nil, managerError(ErrDatabase, str, nil)
	}

	return coinTypePubKeyEnc, coinTypePrivKeyEnc, nil
}