Decryption Example

This example reads the encrypted data from the file created by the Encryption Example (test1.xxx), decrypts it by using the RC2 block cipher, and writes out the plaintext data to another file (test1.txt). The session key used to perform the decryption is read from the ciphertext file.

#include <wincrypt.h>

FILE *hSource = NULL;
FILE *hDest = NULL;
int eof = 0;

HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;

#define BLOCK_SIZE 160
BYTE pbBuffer[BLOCK_SIZE];
DWORD dwCount;

BYTE *pbKeyBlob = NULL;
DWORD dwBlobLen;

// Open the source file.
if((hSource=fopen("test1.xxx","rb"))==NULL) {
    printf("Error opening source file!\n");
    goto done;
}

// Open the destination file.
if((hDest=fopen("test2.txt","wb"))==NULL) {
    printf("Error opening destination file!\n");
    goto done;
}

// Get a handle to the default provider.
if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) {
    printf("Error %x during CryptAcquireContext!\n", GetLastError());
    goto done;
}

// Read the key blob length from the source file and allocate it to memory.
fread(&dwBlobLen, sizeof(DWORD), 1, hSource);
if(ferror(hSource) || feof(hSource)) {
    printf("Error reading file header!\n");
    goto done;
}

if((pbKeyBlob = malloc(dwBlobLen)) == NULL) {
    printf("Out of memory!\n");
    goto done;
}

// Read the key blob from the source file.
fread(pbKeyBlob, 1, dwBlobLen, hSource);
if(ferror(hSource) || feof(hSource)) {
    printf("Error reading file header!\n");
    goto done;
}

// Import the key blob into the CSP.
if(!CryptImportKey(hProv, pbKeyBlob, dwBlobLen, 0, 0, &hKey)) {
    printf("Error %x during CryptImportKey!\n", GetLastError());
    goto done;
}

// Decrypt the source file and write it to the destination file.
do {
    // Read up to BLOCK_SIZE bytes from source file.
    dwCount = fread(pbBuffer, 1, BLOCK_SIZE, hSource);
    if(ferror(hSource)) {
        printf("Error reading data from source file!\n");
        goto done;
    }
    eof=feof(hSource);

    // Decrypt the data.
    if(!CryptDecrypt(hKey, 0, eof, 0, pbBuffer, &dwCount)) {
        printf("Error %x during CryptDecrypt!\n", GetLastError());
        goto done;
    }

    // Write the data to the destination file.
    fwrite(pbBuffer, 1, dwCount, hDest);
    if(ferror(hDest)) {
        printf("Error writing data to destination file!\n");
        goto done;
    }
} while(!feof(hSource));

// If the decryption was successful, The data contained in test2.txt
// should match the data contained in the original test1.txt ( which
// was used as the source for the encryption in the previous section).

done:

// Free memory.
if(pbKeyBlob) free(pbKeyBlob);

// Destroy the session key.
if(hKey != 0) CryptDestroyKey(hKey);

// Release the provider handle.
if(hProv != 0) CryptReleaseContext(hProv, 0);

// Close the source file.
if(hSource != NULL) fclose(hSource);

// Close destination file.
if(hDest != NULL) fclose(hDest);