#include "stdafx.h" #include <windows.h> #include <Wincrypt.h> #include <iostream> #include <cstdlib> #include <stdio.h> #pragma comment(lib,"crypt32.lib") using namespace std; void MyhandlError(char *s) { fprintf(stderr,"This is a error. "); fprintf(stderr ,"Current error :%x. ",GetLastError()); fprintf(stderr,"Error info:%s. ",s); exit(1); } int main(int argc,char* argv[]) { DATA_BLOB Datain; DATA_BLOB DataOut; DATA_BLOB Dataput; BYTE *pbdata = (BYTE*)"Hello word,this is a testing?"; DWORD cbdatalen = strlen((char*)pbdata) + 1; LPWSTR pbtest = NULL; printf("Pbdata len length is %d. ",cbdatalen); Datain.pbData = pbdata; Datain.cbData = cbdatalen; if (CryptProtectData(&Datain,NULL,NULL,NULL,NULL,0,&DataOut)) { printf("The encodeCrypt Dta Is :%s. ",DataOut.pbData); FILE *fp; fp = fopen("1.txt","wb"); fwrite(DataOut.pbData,cbdatalen,1,fp); fclose(fp); }else { MyhandlError("Error in CryptprotecDta. "); } if (CryptUnprotectData(&DataOut,&pbtest,NULL,NULL,NULL,0,&Dataput)) { printf("The decrypted data is: %s ", Dataput.pbData); FILE *fp1; fp1 = fopen("2.txt","wb"); fwrite(Dataput.pbData,cbdatalen,1,fp1); fclose(fp1); }else { MyhandlError("Error in decode. "); } LocalFree(DataOut.pbData); LocalFree(Dataput.pbData); return 0; }
输出:
E:windowsTestDebug>Test.exe
Pbdata len length is 30.
The encodeCrypt Dta Is :..
The decrypted data is: Hello word,this is a testing?