Re: Problem with cryptoapi
Thanks for replying. I am using MS_DEF_PROV while calling
CryptAcquireContext(). The code for generating the key and writing it in a
file is as follows-
//Code for writing key in a file
BOOL CEncryption::WritePrivateKey(FILE* pDestination, HCRYPTKEY
hPrivateKey )
{
BOOL bSuccess = FALSE;
DWORD dwBlobLen = 0;
LPBYTE lpPrivateKey= NULL;
// Get a private key
hPrivateKey = GeneratePrivateKey( &lpPrivateKey, &dwBlobLen,
FILE_ENCRYPT_ALGORITHM );
// If we succeeded in getting a private key...
if( lpPrivateKey )
{
// Write the size of the private key to the destination file
if( fwrite( &dwBlobLen, sizeof(dwBlobLen), 1, pDestination ) )
{
// Write the private key (encrypted) to the destination file
if( fwrite( lpPrivateKey, sizeof(BYTE), dwBlobLen, pDestination ) ==
dwBlobLen )
bSuccess = TRUE;
}
}
return bSuccess;
}
//code for generating the key and exporting the key.
HCRYPTKEY CEncryption::GeneratePrivateKey( LPBYTE* lpPrivateKeyBlob,
LPDWORD lpdwBlobSize,
int enumAlgorithm)
{
CMyApp *pApp=(CMyApp*)AfxGetApp();
//HCRYPTKEY hPrivateKey = NULL;
HCRYPTKEY hPublicKey = NULL;
BOOL /*bInit,*/ bCryptGen;
//Generate the private key
BOOL bSuccess;
if(pApp->Is9x)
{
bSuccess=CryptAcquireContextA( (unsigned long *)&m_hContext,
"My Container", MS_DEF_PROV_A, PROV_RSA_FULL, 0 );
}
else
{
bSuccess = CryptAcquireContext( (unsigned long *)&m_hContext,
_T("My Container"),
/*NULL,//*/MS_DEF_PROV,
PROV_RSA_FULL,
0);
int a = GetLastError();
}
int a = GetLastError();
bCryptGen = CryptGenKey( m_hContext, enumAlgorithm, CRYPT_EXPORTABLE,
&hPrivateKey );
if(bSuccess && bCryptGen)
{
// Get handle to the encrypter's exchange public key
if( CryptGetUserKey(m_hContext, AT_KEYEXCHANGE, &hPublicKey ) )
{
// Determine size of the key blob
if( CryptExportKey( hPrivateKey,
hPublicKey,
SIMPLEBLOB,
0, NULL,
lpdwBlobSize ))
{
(*lpPrivateKeyBlob) = (LPBYTE)malloc( sizeof(BYTE) * (*lpdwBlobSize) );
ATLASSERT( lpPrivateKeyBlob != NULL );
if( lpPrivateKeyBlob )
// Encrypt and export private key
CryptExportKey( hPrivateKey,
hPublicKey,
SIMPLEBLOB,
0,
(*lpPrivateKeyBlob),
lpdwBlobSize );
}
}
}
if( hPublicKey )
CryptDestroyKey( hPublicKey );
return hPrivateKey;
}
"Ashwani" <ashwani@stellarinfo.com> wrote in message
news:#gC1mSgCHHA.992@TK2MSFTNGP03.phx.gbl...
Hi, i am using cryptoapi to encrypt my files. The files are decrypted if i
decrypt them on the same system with same user, but if i try to decrypt
them
with different user or on different system, decryption fails. The function
i
am using to encrypt files are:-
CryptAcquireContext();
CryptGetUserKey( );
CryptGetUserKey( );
GeneratePrivateKey();
CryptGenKey();
etc.
The fuction failing on decryption is
CryptImportKey();
Can anybody tell how to decrypt files on a different system;
Thanks;