Tuesday, September 21, 2010

Obtain the plain text session key using CryptoAPI

Introduction
Generally it's very important to obtain the value of session keys. However, the Microsoft Cryptographic Providers (Base and Enhanced) does not support this feature. CryptExportKey() and CryptImportKey() require a valid key handle to encrypt and decrypt the session key, respectively. MSDN shows a way to do this using a exponent-of-one private key. This article shows a better way to perform the same process. This way is faster and more comprehensive.
It's ready to run, but you must set the following parameters at Project -> Settings (Visual Studio 6.0 ) :
Add in C++/Preprocessor definitions: _WIN32_WINNT=0x0500, _CRYPT32_(WIN2K) or _WIN32_WINNT=0x0400, _CRYPT32_(NT4)
And Link this library crypt32.lib
Code Listing
#include <windows.h>
#include <wincrypt.h>
#define KEY_PAIR_SIZE     dwSize - 12
#define SESSION_KEY_SIZE  dwKeyMaterial
void main()
{
   HCRYPTPROV hProv = 0;
   HCRYPTKEY hExchangeKeyPair = 0;
   HCRYPTKEY hSessionKey = 0;
   BYTE *pbKeyMaterial  = NULL;
   DWORD dwKeyMaterial ;  
   BYTE *pbExportedKeyBlob = NULL;
   BYTE *pbEncryptedKey    = NULL;
   DWORD dwSize;
   unsigned int c;
   __try
   {
       if (!CryptAcquireContext( &hProv, "Container Name",
           MS_ENHANCED_PROV , PROV_RSA_FULL, CRYPT_MACHINE_KEYSET ))
       {
           __leave;
       }

Read more: Codeproject