Decryption Example
This example reads the encrypted data from the file created by the "Encryption
Example" (test1.xxx), decrypts it 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 source file.
if((hSource=fopen("test1.xxx","rb"))==NULL) {
printf("Error opening source file!\n");
goto done;
}
// Open destination file.
if((hDest=fopen("test1.txt","wb"))==NULL) {
printf("Error opening destination file!\n");
goto done;
}
// Get handle to the default provider.
if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) {
printf("Error %x during CryptAcquireContext!\n", GetLastError());
goto done;
}
// Read key blob length from source file and allocate 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 key blob from source file.
fread(pbKeyBlob, 1, dwBlobLen, hSource);
if(ferror(hSource) || feof(hSource)) {
printf("Error reading file header!\n");
goto done;
}
// Import key blob into CSP.
if(!CryptImportKey(hProv, pbKeyBlob, dwBlobLen, 0, 0, &hKey)) {
printf("Error %x during CryptImportKey!\n", GetLastError());
goto done;
}
// Decrypt source file and write to 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 data.
if(!CryptDecrypt(hKey, 0, eof, 0, pbBuffer, &dwCount)) {
printf("Error %x during CryptDecrypt!\n", GetLastError());
goto done;
}
// Write data to destination file.
fwrite(pbBuffer, 1, dwCount, hDest);
if(ferror(hDest)) {
printf("Error writing data to destination file!\n");
goto done;
}
} while(!feof(hSource));
done:
// Free memory.
if(pbKeyBlob) free(pbKeyBlob);
// Destroy session key.
if(hKey != 0) CryptDestroyKey(hKey);
// Release provider handle.
if(hProv != 0) CryptReleaseContext(hProv, 0);
// Close source file.
if(hSource != NULL) fclose(hSource);
// Close destination file.
if(hDest != NULL) fclose(hDest);
- Software for developers
-
Delphi Components
.Net Components
Software for Android Developers
- More information resources
-
MegaDetailed.Net
Unix Manual Pages
Delphi Examples
- Databases for Amazon shops developers
-
Amazon Categories Database
Browse Nodes Database