Click here to Skip to main content
16,004,854 members
Home / Discussions / C / C++ / MFC
   

C / C++ / MFC

 
GeneralRe: initialize stl map in static scope Pin
yccheok23-Sep-05 1:19
yccheok23-Sep-05 1:19 
AnswerRe: initialize stl map in static scope Pin
Tim Smith23-Sep-05 3:58
Tim Smith23-Sep-05 3:58 
AnswerRe: pointer to char array Pin
Eytukan22-Sep-05 23:02
Eytukan22-Sep-05 23:02 
GeneralRe: pointer to char array Pin
sunit523-Sep-05 2:56
sunit523-Sep-05 2:56 
GeneralRe: pointer to char array Pin
ThatsAlok23-Sep-05 17:53
ThatsAlok23-Sep-05 17:53 
AnswerRe: pointer to char array Pin
FarPointer23-Sep-05 1:22
FarPointer23-Sep-05 1:22 
QuestionA very urgent problem Pin
momer22-Sep-05 22:17
momer22-Sep-05 22:17 
QuestionCryptEncrypt and CryptDecrypt functions of CryptoApi problems Pin
naeemnimi22-Sep-05 21:49
naeemnimi22-Sep-05 21:49 
Hello:

I am having following error while using CryptEncrypt and CryptDecrypt for public private key pair of Windows CryptoApi .I am using windowsXP as OS.

The code of the class I am using is given below. I am having problem while using Encrypt and Decrypt functions of the class. Can anybody would tell me where is the error and how to remove it or could make the code right where error occurs.

Thanks,
Naeem




//////////////////////////////Header File/////////////////////////
#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <wincrypt.h>
#include <tchar.h>

// Helper class definition to generate and export Public/Private keys
// for Asymmetric encryption. The semantics for usage are:
// Call AcquireContext with a container name, call
// GenerateKeyPair next and then call ExportPublicKey or
// ExportPrivateKey.
class CryptoHelper
{
private:
HCRYPTPROV m_hCryptProv;
HCRYPTKEY m_hSessionKey;
BYTE *m_pPublicKey;
BYTE *m_pPrivateKey;
BYTE *m_pEncSessionKey;
DWORD dwPrivateKeyLen;
DWORD dwPublicKeyLen;
DWORD dwEncSessionKeyLen;

public:
HCRYPTKEY m_hCryptKey;
CryptoHelper();
~CryptoHelper();
HRESULT AcquireContext(LPCTSTR wszContainerName);
HRESULT GenerateKeyPair();

HRESULT ExportPublicKey(BYTE **ppPublicKey, DWORD &cbKeySize);;
HRESULT ExportPrivateKey(BYTE **ppPrivateKey, DWORD &cbKeySize);
void Encrypt(char **Input,char **Output,DWORD &dwLen);
void Decrypt(char **Input,char **Output,DWORD &dwLen);

};


//////////////////////////////The CPP File/////////////////////////

#include "CryptoHelper.h"
#include <stdio.h>
//#include "Cspdk.h"
// The RSA public-key key exchange algorithm
#define ENCRYPT_ALGORITHM CALG_RSA_KEYX
// The high order WORD 0x0200 (decimal 512)
// determines the key length in bits.
#define KEYLENGTH 0x02000000
#define SESS_KEYLENGTH 0x00800000 //128 Bit
//--------------------------------------------------------------------
// The constructor initializes the member variables
// to NULL.
//--------------------------------------------------------------------
CryptoHelper::CryptoHelper()
{
m_hCryptProv = NULL;
m_hCryptKey = NULL;
m_hSessionKey = NULL;
m_pPublicKey=NULL;
m_pPrivateKey=NULL;
m_pEncSessionKey=NULL;
dwPrivateKeyLen=0;
dwPublicKeyLen=0;
dwEncSessionKeyLen=0;
}
//--------------------------------------------------------------------
// The destructor releases the handles acquired
// when an object goes out of scope.
//--------------------------------------------------------------------
CryptoHelper::~CryptoHelper()
{
if (m_hCryptProv)
{
CryptReleaseContext(m_hCryptProv,0);
m_hCryptProv = NULL;
}
if (m_hCryptKey)
m_hCryptKey = NULL;

}

//--------------------------------------------------------------------
// This method calls the CryptAcquireContext function
// to get a handle to a key container owned by the the
// Microsoft Enhanced Cryptographic Provider.
//--------------------------------------------------------------------
HRESULT CryptoHelper::AcquireContext(LPCTSTR wszContainerName)
{
HRESULT hr = S_OK;
DWORD dwErrCode;
// Release a previously acquired handle to the key container.
if (m_hCryptProv != NULL)
{
CryptReleaseContext(m_hCryptProv,0);
m_hCryptProv = NULL;
}
// Release a previously acquired handle to key-pair.
if (m_hCryptKey != NULL)
m_hCryptKey = NULL;
// Attempt to acquire a context and a key container.
// The context will use Microsoft Enhanced Cryptographic
// Provider for the RSA_FULL provider type.
if(!CryptAcquireContext(&m_hCryptProv,
/*NULL*/wszContainerName,
/*NULL*/MS_ENHANCED_PROV,
PROV_RSA_FULL,
CRYPT_MACHINE_KEYSET))
{
// An error occurred in acquiring the context. This could mean
// that the key container requested does not exist. In this case,
// the function can be called again to attempt to create a new key
// container.
if (GetLastError() == NTE_BAD_KEYSET)
{
if(!CryptAcquireContext(&m_hCryptProv,
/*NULL*/wszContainerName,
/*NULL*/MS_ENHANCED_PROV,
PROV_RSA_FULL,
CRYPT_MACHINE_KEYSET|CRYPT_NEWKEYSET))
{
dwErrCode = GetLastError();
return HRESULT_FROM_WIN32(dwErrCode);
}
}
else
{
dwErrCode = GetLastError();
return HRESULT_FROM_WIN32(dwErrCode);
}
}
return hr;
}
//--------------------------------------------------------------------

// This method calls the CryptGenKey function to get a handle to an

// exportable key-pair. The key-pair is generated with the RSA public-key
// key exchange algorithm using Microsoft Enhanced Cryptographic Provider.
//--------------------------------------------------------------------
HRESULT CryptoHelper::GenerateKeyPair()
{
HRESULT hr = S_OK;
DWORD dwErrCode;
// If the handle to key container is NULL, fail.
if (m_hCryptProv == NULL)
return E_FAIL;
// Release a previously acquired handle to key-pair.
if (m_hCryptKey)
m_hCryptKey = NULL;
// Call the CryptGenKey method to get a handle
// to a new exportable key-pair.
if(!CryptGenKey(m_hCryptProv,
ENCRYPT_ALGORITHM,
KEYLENGTH | CRYPT_EXPORTABLE,
&m_hCryptKey))
{
dwErrCode = GetLastError();
return HRESULT_FROM_WIN32(dwErrCode);
}
return hr;
}
//--------------------------------------------------------------------
// This method calls the CryptExportKey function to get the Public key
// in a byte array. The byte array is allocated on the heap and the size
// of this is returned to the caller. The caller is responsible for releasing // this memory using a delete call.
//--------------------------------------------------------------------
HRESULT CryptoHelper::ExportPublicKey(BYTE **ppPublicKey, DWORD &cbKeySize)
{
HRESULT hr = S_OK;
DWORD dwErrCode;
DWORD dwBlobLen;
BYTE *pbKeyBlob = NULL;
// If the handle to key container is NULL, fail.
if (m_hCryptKey == NULL)
return E_FAIL;
// This call here determines the length of the key
// blob.
if(!CryptExportKey(
m_hCryptKey,
NULL,
PUBLICKEYBLOB,
0,
NULL,
&dwBlobLen))
{
dwErrCode = GetLastError();
return HRESULT_FROM_WIN32(dwErrCode);
}
// Allocate memory for the pbKeyBlob.
if((pbKeyBlob = new BYTE[dwBlobLen]) == NULL)
{
return E_OUTOFMEMORY;
}
// Do the actual exporting into the key BLOB.
if(!CryptExportKey(
m_hCryptKey,
NULL,
PUBLICKEYBLOB,
0,
pbKeyBlob,
&dwBlobLen))
{
delete pbKeyBlob;
dwErrCode = GetLastError();
return HRESULT_FROM_WIN32(dwErrCode);
}
else
{
*ppPublicKey = pbKeyBlob;
m_pPublicKey =pbKeyBlob;
cbKeySize = dwBlobLen;
dwPublicKeyLen=dwBlobLen;
}
return hr;
}
//--------------------------------------------------------------------
// This method calls the CryptExportKey function to get the Private key
// in a byte array. The byte array is allocated on the heap and the size
// of this is returned to the caller. The caller is responsible for releasing // this memory using a delete call.
//--------------------------------------------------------------------
HRESULT CryptoHelper::ExportPrivateKey(BYTE **ppPrivateKey, DWORD &cbKeySize)
{
HRESULT hr = S_OK;
DWORD dwErrCode;
DWORD dwBlobLen;
BYTE *pbKeyBlob;
// If the handle to key container is NULL, fail.
if (m_hCryptKey == NULL)
return E_FAIL;
// This call here determines the length of the key
// blob.
if(!CryptExportKey(
m_hCryptKey,
NULL,
PRIVATEKEYBLOB,
0,
NULL,
&dwBlobLen))
{
dwErrCode = GetLastError();
return HRESULT_FROM_WIN32(dwErrCode);
}
// Allocate memory for the pbKeyBlob.
if((pbKeyBlob = new BYTE[dwBlobLen]) == NULL)
{
return E_OUTOFMEMORY;
}

// Do the actual exporting into the key BLOB.
if(!CryptExportKey(
m_hCryptKey,
NULL,
PRIVATEKEYBLOB,
0,
pbKeyBlob,
&dwBlobLen))
{
delete pbKeyBlob;
dwErrCode = GetLastError();
return HRESULT_FROM_WIN32(dwErrCode);
}
else
{
*ppPrivateKey = pbKeyBlob;
m_pPrivateKey=pbKeyBlob;
cbKeySize = dwBlobLen;
dwPrivateKeyLen=dwBlobLen;
}
return hr;
}
////////////////////////the function with problem//////////////////
void CryptoHelper::Encrypt(char **Input,char **Output,DWORD &dwLen)
{//dwLen in start gives input string length on return it gives output string
//length
HCRYPTKEY hPubKey=NULL;
HCRYPTHASH hHash=NULL;
DWORD dwBufLen;

//importing the public key . In real situation this would be the //public key of other user a
if(CryptImportKey(m_hCryptProv,m_pPublicKey,dwPublicKeyLen,0,CRYPT_EXPORTABLE,
&hPubKey))
{
MessageBox(NULL,"public key achieved","",MB_OK);
}

if(CryptEncrypt(hPubKey,0,TRUE,0,NULL,&dwBufLen,dwLen))//get //length to hold buffer but this fails
{
dwBufLen=dwLen;
*Output=new char[dwLen+1];
memset(*Output,0,dwLen+1);
memcpy(*Output,*Input,dwLen);

if(!CryptEncrypt(hPubKey,0,TRUE,0,(BYTE*)*Output,&dwBufLen,dwLen))
{
::MessageBox(NULL,"Fail","",MB_OK);
dwLen=0;
}
else
dwLen=dwBufLen;
}
}


void CryptoHelper::Decrypt(char **Input,char **Output,DWORD &dwLen)
{
//now first get the session key from the Encrypted Session key
HCRYPTKEY hSessionKey=NULL,hPrvtKey;
DWORD dwBufLen;
if(CryptImportKey(m_hCryptProv,m_pPrivateKey,dwPrivateKeyLen,0,CRYPT_EXPORTABLE,
&hPrvtKey))
{
MessageBox(NULL,"private key achieved","",MB_OK);
}

if(CryptDecrypt(hPrvtKey,0,TRUE,0,NULL,&dwBufLen))//get //length to hold buffer but this fails
{

*Output=new char[dwBufLen+1];
memset(*Output,0,dwBufLen+1);
memcpy(*Output,*Input,dwLen);

if(!CryptDecrypt(hPrvtKey,0,TRUE,0,(BYTE*)*Output,&dwBufLen))
{
::MessageBox(NULL,"Fail","",MB_OK);
dwLen=0;
}
else
dwLen=dwBufLen;
}


}

//////////////////////////////The Main File/////////////////////////
#include <stdio.h>
#include "CryptoHelper.h"

void main()
{

CryptoHelper cryptoHlpr;
BYTE *pbPublicKey = NULL, *pbPrivateKey = NULL;
DWORD dwPublicKeySize = 0,dwPrivateKeySize = 0;
HRESULT hr = S_OK;
// Get the key container context.

if (FAILED(hr = cryptoHlpr.AcquireContext(("TestContainer"))))
{
// Call FormatMessage to display the error returned in hr.
return;
}
// Generate the public/private key pair.
if (FAILED(hr = cryptoHlpr.GenerateKeyPair()))
{
// Call FormatMessage to display the error returned in hr.
return;
}
// Export out the public key blob.
cryptoHlpr.ExportPublicKey(&pbPublicKey, dwPublicKeySize);

// Export out the private key blob.
cryptoHlpr.ExportPrivateKey(&pbPrivateKey, dwPrivateKeySize);



//now encrypting the text
char *input="abcdef123456";
char *output,*Result;
DWORD dwLen=strlen(input);
cryptoHlpr.Encrypt(&input,&output,dwLen);//error

//now decrypting the text
cryptoHlpr.Decrypt(&output,&Result,dwLen);//error

if (pbPublicKey)
delete [] pbPublicKey;
// Delete the private key blob allocated by the
// ExportPrivateKey method.
if (pbPrivateKey)
delete [] pbPrivateKey;
return;
}
AnswerRe: CryptEncrypt and CryptDecrypt functions of CryptoApi problems Pin
Elmue6-Sep-10 9:51
Elmue6-Sep-10 9:51 
Questioni need help to fix the histogram.plz Pin
davidcooler22-Sep-05 21:26
davidcooler22-Sep-05 21:26 
JokeRe: i need help to fix the histogram.plz Pin
khan++22-Sep-05 21:43
khan++22-Sep-05 21:43 
GeneralRe: i need help to fix the histogram.plz Pin
David Crow23-Sep-05 3:46
David Crow23-Sep-05 3:46 
AnswerRe: i need help to fix the histogram.plz Pin
David Crow23-Sep-05 3:32
David Crow23-Sep-05 3:32 
QuestionHow to place the child Dialogs on TaskBar???? Pin
G.Radhakrishna22-Sep-05 20:48
G.Radhakrishna22-Sep-05 20:48 
AnswerRe: How to place the child Dialogs on TaskBar???? Pin
prasad_som22-Sep-05 21:17
prasad_som22-Sep-05 21:17 
Questionrespond message Pin
Member 216100422-Sep-05 20:41
Member 216100422-Sep-05 20:41 
AnswerRe: respond message Pin
Cedric Moonen22-Sep-05 20:49
Cedric Moonen22-Sep-05 20:49 
GeneralRe: respond message Pin
Member 216100422-Sep-05 21:45
Member 216100422-Sep-05 21:45 
GeneralRe: respond message Pin
Eytukan22-Sep-05 22:24
Eytukan22-Sep-05 22:24 
QuestionDoes anyone know where is dlibtiff.lib??? Pin
asifrogers22-Sep-05 20:38
asifrogers22-Sep-05 20:38 
AnswerRe: Does anyone know where is dlibtiff.lib??? Pin
Mircea Puiu23-Sep-05 3:00
Mircea Puiu23-Sep-05 3:00 
Questiondoubt about exe file? Pin
G Haranadh22-Sep-05 20:24
G Haranadh22-Sep-05 20:24 
AnswerRe: doubt about exe file? Pin
khan++22-Sep-05 21:51
khan++22-Sep-05 21:51 
AnswerRe: doubt about exe file? Pin
James Brown22-Sep-05 21:59
James Brown22-Sep-05 21:59 
AnswerRe: doubt about exe file? Pin
Alexander M.,23-Sep-05 2:47
Alexander M.,23-Sep-05 2:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.