// DerivePrivKey attempts to derive the private key that corresponds to the
// passed key descriptor.
//
// NOTE: This is part of the keychain.SecretKeyRing interface.
497622
func (b *BtcWalletKeyRing) DerivePrivKey(keyDesc KeyDescriptor) (*btcec.PrivateKey, error) {
	var key *btcec.PrivateKey

	db := b.wallet.Database()
	err := walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
		addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)

		scope, err := b.keyScope()
		if err != nil {
			return err
		}

		// If the account doesn't exist, then we may need to create it
		// for the first time in order to derive the keys that we
		// require.
		err = b.createAccountIfNotExists(
			addrmgrNs, keyDesc.Family, scope,
		)
		if err != nil {
			return err
		}

		// If the public key isn't set or they have a non-zero index,
		// then we know that the caller instead knows the derivation
		// path for a key.
		if keyDesc.PubKey == nil || keyDesc.Index > 0 {
			// Now that we know the account exists, we can safely
			// derive the full private key from the given path.
			path := waddrmgr.DerivationPath{
				Account: uint32(keyDesc.Family),
				Branch:  0,
				Index:   uint32(keyDesc.Index),
			}
			addr, err := scope.DeriveFromKeyPath(addrmgrNs, path)
			if err != nil {
				return err
			}

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

			return nil
		}

		// If the public key isn't nil, then this indicates that we
		// need to scan for the private key, assuming that we know the
		// valid key family.
		nextPath := waddrmgr.DerivationPath{
			Account: uint32(keyDesc.Family),
			Branch:  0,
			Index:   0,
		}

		// We'll now iterate through our key range in an attempt to
		// find the target public key.
		//
		// TODO(roasbeef): possibly move scanning into wallet to allow
		// to be parallelized
		for i := 0; i < MaxKeyRangeScan; i++ {
			// Derive the next key in the range and fetch its
			// managed address.
			addr, err := scope.DeriveFromKeyPath(
				addrmgrNs, nextPath,
			)
			if err != nil {
				return err
			}
			managedAddr := addr.(waddrmgr.ManagedPubKeyAddress)

			// If this is the target public key, then we'll return
			// it directly back to the caller.
			if managedAddr.PubKey().IsEqual(keyDesc.PubKey) {
				key, err = managedAddr.PrivKey()
				if err != nil {
					return err
				}

				return nil
			}

			// This wasn't the target key, so roll forward and try
			// the next one.
			nextPath.Index++
		}

		// If we reach this point, then we we're unable to derive the
		// private key, so return an error back to the user.
		return ErrCannotDerivePrivKey
	})
	if err != nil {
		return nil, err
	}

	return key, nil
}
110596
func savePrivateKey(key crypto.PrivateKey) ([]byte, error) {
	var pemType string
	var keyBytes []byte
	switch key := key.(type) {
	case *ecdsa.PrivateKey:
		var err error
		pemType = "EC"
		keyBytes, err = x509.MarshalECPrivateKey(key)
		if err != nil {
			return nil, err
		}
	case *rsa.PrivateKey:
		pemType = "RSA"
		keyBytes = x509.MarshalPKCS1PrivateKey(key)
	}

	pemKey := pem.Block{Type: pemType + " PRIVATE KEY", Bytes: keyBytes}
	return pem.EncodeToMemory(&pemKey), nil
}
834173
func (s *PerUserKeySeed) derivePrevKey() (res NaclSecretBoxKey, err error) {
	return s.DeriveSymmetricKey(DeriveReasonPUKPrev)
}
534040
func deriveKey(passphrase string, salt []byte) [keyLength]byte {
	secretKeyBytes := argon2.IDKey([]byte(passphrase), salt, 4, 64*1024, 4, 32)
	var secretKey [keyLength]byte
	copy(secretKey[:], secretKeyBytes)
	return secretKey
}
796439
func DeriveSharedSecret(private PrivateKey, public PublicKey) ([]byte, error) {
	// Create context for the shared secret derivation
	dhCtx := C.EVP_PKEY_CTX_new(private.evpPKey(), nil)
	if dhCtx == nil {
		return nil, errors.New("failed creating shared secret derivation context")
	}
	defer C.EVP_PKEY_CTX_free(dhCtx)

	// Initialize the context
	if int(C.EVP_PKEY_derive_init(dhCtx)) != 1 {
		return nil, errors.New("failed initializing shared secret derivation context")
	}

	// Provide the peer's public key
	if int(C.EVP_PKEY_derive_set_peer(dhCtx, public.evpPKey())) != 1 {
		return nil, errors.New("failed adding peer public key to context")
	}

	// Determine how large of a buffer we need for the shared secret
	var buffLen C.size_t
	if int(C.EVP_PKEY_derive(dhCtx, nil, &buffLen)) != 1 {
		return nil, errors.New("failed determining shared secret length")
	}

	// Allocate a buffer
	buffer := C.X_OPENSSL_malloc(buffLen)
	if buffer == nil {
		return nil, errors.New("failed allocating buffer for shared secret")
	}
	defer C.X_OPENSSL_free(buffer)

	// Derive the shared secret
	if int(C.EVP_PKEY_derive(dhCtx, (*C.uchar)(buffer), &buffLen)) != 1 {
		return nil, errors.New("failed deriving the shared secret")
	}

	secret := C.GoBytes(unsafe.Pointer(buffer), C.int(buffLen))
	return secret, nil
}
105211
func (c *Ctx) UsePrivateKey(key PrivateKey) error {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()
	c.key = key
	if int(C.SSL_CTX_use_PrivateKey(c.ctx, key.evpPKey())) != 1 {
		return errorFromErrorQueue()
	}
	return nil
}
937153
func deriveClientKey(clientKey [32]byte, bucket, object string) [32]byte {
	var key [32]byte
	mac := hmac.New(sha256.New, clientKey[:])
	mac.Write([]byte(crypto.SSEC.String()))
	mac.Write([]byte(path.Join(bucket, object)))
	mac.Sum(key[:0])
	return key
}
1069665
func (cs *CryptoService) GetPrivateKey(keyID string) (k data.PrivateKey, role data.RoleName, err error) {
	for _, ks := range cs.keyStores {
		if k, role, err = ks.GetKey(keyID); err == nil {
			return
		}
		switch err.(type) {
		case trustmanager.ErrPasswordInvalid, trustmanager.ErrAttemptsExceeded:
			return
		default:
			continue
		}
	}
	return // returns whatever the final values were
}
673404
func (sk *SecretKey) DeriveKey(password *[]byte) error {
	if err := sk.deriveKey(password); err != nil {
		return err
	}

	// verify password
	digest := sha256.Sum256(sk.Key[:])
	if subtle.ConstantTimeCompare(digest[:], sk.Parameters.Digest[:]) != 1 {
		return ErrInvalidPassword
	}

	return nil
}
868384
func GeneratePublicPrivateKey() ([]byte, []byte, error) {
	var scalar, public [32]byte

	if _, err := io.ReadFull(rand.Reader, scalar[:]); err != nil {
		return nil, nil, err
	}

	curve25519.ScalarBaseMult(&public, &scalar)
	return public[:], scalar[:], nil
}
241876
func GenPrivKeyFromSecret(secret []byte) PrivKeyEd25519 {
	seed := crypto.Sha256(secret) // Not Ripemd160 because we want 32 bytes.

	privKey := ed25519.NewKeyFromSeed(seed)
	var privKeyEd PrivKeyEd25519
	copy(privKeyEd[:], privKey)
	return privKeyEd
}
346810
func (s *ScopedKeyManager) deriveKey(acctInfo *accountInfo, branch,
	index uint32, private bool) (*hdkeychain.ExtendedKey, error) {

	// Choose the public or private extended key based on whether or not
	// the private flag was specified.  This, in turn, allows for public or
	// private child derivation.
	acctKey := acctInfo.acctKeyPub
	if private {
		acctKey = acctInfo.acctKeyPriv
	}

	// Derive and return the key.
	branchKey, err := acctKey.Child(branch)
	if err != nil {
		str := fmt.Sprintf("failed to derive extended key branch %d",
			branch)
		return nil, managerError(ErrKeyChain, str, err)
	}

	addressKey, err := branchKey.Child(index)
	branchKey.Zero() // Zero branch key after it's used.
	if err != nil {
		str := fmt.Sprintf("failed to derive child extended key -- "+
			"branch %d, child %d",
			branch, index)
		return nil, managerError(ErrKeyChain, str, err)
	}

	return addressKey, nil
}
572018
func GeneratePrivateKey() [keySize]byte {
	var b [keySize]byte
	rand.Read(b[:])

	return b
}
714643
func WithPrivateKey(key []byte) SigningIdentityOption {
	return func(o *IdentityOption) error {
		o.PrivateKey = key
		return nil
	}
}
665938
func GeneratePrivateAccount() (*PrivateAccount, error) {
	privateKey, err := crypto.GeneratePrivateKey(nil, crypto.CurveTypeEd25519)
	if err != nil {
		return nil, err
	}
	publicKey := privateKey.GetPublicKey()
	return ConcretePrivateAccount{
		Address:    publicKey.GetAddress(),
		PublicKey:  publicKey,
		PrivateKey: privateKey,
	}.PrivateAccount(), nil
}
1056748
func (s *APNSVoipSandboxChannelRequest) SetPrivateKey(v string) *APNSVoipSandboxChannelRequest {
	s.PrivateKey = &v
	return s
}
350959
func DeriveKey(keyHash *chainhash.Hash) [gcs.KeySize]byte {
	var key [gcs.KeySize]byte
	copy(key[:], keyHash.CloneBytes()[:])
	return key
}