本示例从“加密示例”(test1.xxx)创建的文件中读取加密数据,使用RC2块密码对其进行解密,并将明文数据写入另一个文件(test1.txt)。从密文文件中读取用于执行解密的会话密钥。
#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;
//打开源文件。
if((hSource=fopen("test1.xxx","rb"))==NULL) {
printf("Error opening source file!\n");
goto done;
}
//打开目标文件。
if((hDest=fopen("test1.txt","wb"))==NULL) {
printf("Error opening destination file!\n");
goto done;
}
//获取默认提供程序的句柄。
if(!CryptAcquireContext(& hProv,NULL,NULL,PROV_RSA_FULL,0)){
printf("Error %x during CryptAcquireContext!\n", GetLastError());
goto done;
}
//从源文件读取密钥blob长度并分配内存。
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;
}
//从源文件读取密钥blob。
fread(pbKeyBlob, 1, dwBlobLen, hSource);
if(ferror(hSource)|| feof(hSource)){
printf("Error reading file header!\n");
goto done;
}
//将关键字blob导入CSP。
if(!CryptImportKey(hProv,pbKeyBlob,dwBlobLen,0,0,& hKey)){
printf("Error %x during CryptImportKey!\n", GetLastError());
goto done;
}
//解密源文件并写入目标文件。
do {
//从源文件读取BLOCK_SIZE个字节。
dwCount = fread(pbBuffer, 1, BLOCK_SIZE, hSource);
if(ferror(hSource)){
printf("Error reading data from source file!\n");
goto done;
}
eof=feof(hSource);
//解密数据
if(!CryptDecrypt(hKey,0,eof,0,pbBuffer,& dwCount)){
printf("Error %x during CryptDecrypt!\n", GetLastError());
goto done;
}
//将数据写入目标文件。
fwrite(pbBuffer, 1, dwCount, hDest);
if(ferror(hDest)){
printf("Error writing data to destination file!\n");
goto done;
}
} while(!feof(hSource));
完成:
//空闲内存
if(pbKeyBlob) free(pbKeyBlob);
//销毁会话密钥。
if(hKey != 0) CryptDestroyKey(hKey);
//发布提供者句柄。
if(hProv != 0) CryptReleaseContext(hProv, 0);
//关闭源文件。
if(hSource != NULL) fclose(hSource);
//关闭目的地文件。
if(hDest != NULL) fclose(hDest);