i call CryptExportKey to get size of key, for buffer allocation
when i allocate buffer and use it in CryptExportKey again to actually export key, i get error ERROR_MORE_DATA
i decided print size, it turned out to be 148 (suspiciously small, probably thats why i get ERROR_MORE_DATA from next call)
so can anyone tell me whats wrong here ?
CryptExportKey(hKey,NULL,PUBLICKEYBLOB,0,NULL,&PublicKeySize)
PS CryptoApi gave error 87, because it turned out that last param (pointer to output size dword) should be set zero while i was not doing this because msdn was silent about this,
and this crap took me a while (about 10 days) to figure out (damn am i stupid ?), msdn is not documenting everything, and error values are too ambiguous
PPS i already spent 3 weeks figuring out how to use cryptoapi, and googled every possible tutorial\example that you will probably link . . .
PPPS i will post "source code"
#include <Windows.h>
#include <WinCrypt.h>
#include "ErrorLog.h" // PPPPS this is printf wrapper
#include "memory.h" // GlobalAlloc wrapper with error check
DWORD Keys(){
HCRYPTPROV hCryptProv;
HCRYPTKEY hKey;
DWORD PublicKeySize=0;
PBYTE PublicKey;
//acquire context
if(!CryptAcquireContext(&hCryptProv,"MyContainer1",NULL,PROV_RSA_FULL,0)){
error("CryptAcquireContext",GetLastError());
if(!CryptAcquireContext(&hCryptProv,"MyContainer1",NULL,PROV_RSA_FULL,CRYPT_NEWKEYSET)){
error("CryptAcquireContext",GetLastError());
return 1;
}
}
if(!CryptGenKey(hCryptProv,AT_KEYEXCHANGE,CRYPT_ARCHIVABLE,&hKey)){
error("CryptGenKey",GetLastError());
CryptReleaseContext(hCryptProv,0);
return 1;
}
error("Key Generated",0);
if(!CryptExportKey(hKey,NULL,PUBLICKEYBLOB,0,NULL,&PublicKeySize)){
error("CryptExportKey SIZE",GetLastError());
CryptReleaseContext(hCryptProv,0);
CryptDestroyKey(hKey);
return 1;
}
error("pkey size",PublicKeySize);
PublicKey = (PBYTE)Alloc(PublicKeySize);
if(!PublicKey){
goto FAIL_PKEY_ALLOC;
}
PublicKeySize=0;
if(!CryptExportKey(hKey,NULL,PUBLICKEYBLOB,0,PublicKey,&PublicKeySize)){
error("CryptExportKey KEY",GetLastError());
FAIL_PKEY_ALLOC:
CryptReleaseContext(hCryptProv,0);
CryptDestroyKey(hKey);
return 1;
}
/// /// /// under construction /// /// ///
return 0;
}