This is a mirror of official site: http://jasper-net.blogspot.com/

How to export and import plain text session keys by using CryptoAPI

| Sunday, June 20, 2010
Sometimes it is convenient to export and import plain text session keys. However, the Microsoft Cryptographic Providers (Base and Enhanced) do not support this feature. Both CryptExportKey() and CryptImportKey() require a valid key handle to encrypt and decrypt the session key, respectively. But by using an "exponent-of-one" private key the same effect can be achieved to encrypt and decrypt the session key.

Because the key exponent is one, both the encryption and decryption do nothing to the plain text, and thus essentially leave the session key in plain text.

The following sample code illustrates how to implement this feature:

#include <windows.h>
#include <wincrypt.h>
#include <stdio.h>

void main()
{
  HCRYPTPROV hProv = 0;
  HCRYPTKEY hPubPrivKey = 0;
  HCRYPTKEY hSessionKey = 0;
  BOOL fResult;
  LPBYTE pbKeyMaterial  = NULL;
  DWORD dwKeyMaterial ;  
  int n;

  __try
  {
     printf("Creating Exponent of One Private Key.\n\n");

     // Create Exponent of One private key
     fResult = CreatePrivateExponentOneKey(MS_ENHANCED_PROV, PROV_RSA_FULL,
                                           "TestContainer", AT_KEYEXCHANGE,
                                           &hProv, &hPubPrivKey);
     if (!fResult)
     {
        printf("CreatePrivateExponentOneKey failed with %x\n", GetLastError());
        __leave;
     }

     // Allocate memory for 3DES key and
     // Fill key with data 1,2,3,... in this case
     pbKeyMaterial = (LPBYTE)LocalAlloc(LPTR, 192/8);
     for (n = 0; n < 192/8; n++) pbKeyMaterial[n] = n+1;
     dwKeyMaterial = 192/8;

     printf("\nImporting 3DES key with key material 1,2,3,...\n");

     // Import this key and get an HCRYPTKEY handle
     if (!ImportPlainSessionBlob(hProv, hPubPrivKey, CALG_3DES, pbKeyMaterial, dwKeyMaterial, &hSessionKey))
     {
        printf("ImportPlainSessionBlob failed with %x\n", GetLastError());
        __leave;
     }

     LocalFree(pbKeyMaterial);
     pbKeyMaterial = NULL;

Read more: MS Support

Posted via email from .NET Info

0 comments: