I have two classes, TProvider and TEncrypt. The calling application will talk to the TProvider class. The calling application will call Initialise first to obtain the handle mhProvider. I require access to this handle later when i try to perform encryption, as the TEncrypt class donot have access to this handle mhProvider. How can i get access to this handle?
class TProvider
{
public:
int Initialise();
int Encrypt();
private:
HCRYPTPROV mhProvider;
TEncrypt* mpEncrypt;
};
//------------------------------------
class TEncrypt
{
public:
int Encryption();
private:
int GenerateEncryptionKey();
HCRYPTKEY mhKey;
};
//------------------------------------
int TEncrypt::Encryption()
{
vStatus = GenerateEncryptionKey();
// will go on to perform encryption after obtaining the key
return(vStatus);
}
//------------------------------------
int TEncrypt::GenerateEncryptionKey()
{
BOOL bRet = CryptGenKey(mhProvider,
CALG_AES_256,
CRYPT_EXPORTABLE,
&mhKey);
}
Either you pass the handle to TEncrypt via a (constructor/method) parameter, or you make it available via a global variable. I would prefer the former, as global variables make the code harder to understand, maintain and test.
Availability may also be indirect, e.g. you pass an object to
TEncrypt::Encryption()which provides access to the handle via one of its public methods.(of course you can also pass it through a file, DB, … but let’s keep the focus within the program.)
Update: an example
Note: I renamed
TEncrypt::Encryptbecause it is better to use verbs as method names rather than nouns.