// EGPublicKey::CopyFromPrivateKey
// Copies public key from a private key.  Existing key (if any) is replaced.  This
// method takes the binary rep of the private key and drops the private portion
// to generate the public key.
void
EGPublicKey::CopyFromPrivateKey(const EGPrivateKey& theKeyR)
{
	ClearLocal();

	try
	{
		ByteQueue aPrivQueue;
		aPrivQueue.Put(theKeyR.GetKey(), theKeyR.GetKeyLen());
		aPrivQueue.Close();

		ElGamalVerifier aKey(aPrivQueue);
		ByteQueue       aPubQueue;
		aKey.DEREncode(aPubQueue);
		aPubQueue.Close();

		AllocKeyBuf(aPubQueue.MaxRetrieveable());
		aPubQueue.Get(mKey, mKeyLen);
	}
	catch (Exception& anEx)
	{
		WDBG_AH("EGPublicKey::CopyFromPrivateKey Caught CryptoLib exception: " << anEx.what());
#ifndef _WONCRYPT_NOEXCEPTIONS
		throw WONCrypt::CryptException(WONCommon::ExCryptoLib, __LINE__, __FILE__, anEx.what());
#else
		Invalidate();
#endif
	}
}
// EGPublicKey::Encrypt
// Encrypts a block of data of the specified length using ElGamal encryption for this
// key.  Returns allocated block/len of encrypted data.
EGPublicKey::CryptReturn
EGPublicKey::Encrypt(const void* theMsgP, unsigned long theLen) const
{
	WTRACE("EGPublicKey::Encrypt");

	// Sanity check
	if ((! theMsgP) || (theLen == 0))
	{
		WDBG_LM("EGPublicKey::Encrypt No data to encrypt");
		return CryptReturn(NULL,0);
	}

	try
	{
		// Allocate crypt object if needed
		AllocateCrypt();

		// Encrypt the data
		ByteQueue aQueue;
		EncryptData(aQueue, reinterpret_cast<const unsigned char*>(theMsgP), theLen);

		// Build return
		WDBG_LL("EGPublicKey::Encrypt Building return values.");
		unsigned long anOutLen = aQueue.MaxRetrieveable();
		if (anOutLen == 0)
		{
			WDBG_LM("EGPublicKey::Encrypt Encrypt failed, no data.");
			return CryptReturn(NULL, 0);
		}

		auto_ptr<unsigned char> anOutP(new unsigned char [anOutLen]);
		aQueue.Get(anOutP.get(), anOutLen);

		WDBG_LM("EGPublicKey::Encrypt Encrypted, out block len=" << anOutLen);
		return CryptReturn(anOutP.release(), anOutLen);
	}
	catch (Exception& anEx)
	{
		// Little trick here, construct a CryptException to auto log the failure!
		WDBG_AH("EGPublicKey::Encrypt Caught CryptoLib exception: " << anEx.what());
#ifndef _WONCRYPT_NOEXCEPTIONS
		WONCrypt::CryptException aLog(WONCommon::ExCryptoLib, __LINE__, __FILE__, anEx.what());
#endif
		return CryptReturn(NULL,0);
	}
}