仅供参考#pragmacomment(lib,"crypt32.lib")
#pragmacomment(lib,"advapi32.lib")
#define_WIN32_WINNT0x0400
#include
#include
#include
#defineMY_ENCODING_TYPE(PKCS_7_ASN_ENCODING|X509_ASN_ENCODING)
#defineKEYLENGTH0x00800000
voidHandleError(char*s);
//--------------------------------------------------------------------
//Theseadditional#definestatementsarerequired.
#defineENCRYPT_ALGORITHMCALG_RC4
#defineENCRYPT_BLOCK_SIZE8
//DeclarethefunctionEncryptFile.Thefunctiondefinition
//followsmain.
BOOLEncryptFile(
PCHARszSource,
PCHARszDestination,
PCHARszPassword);
//--------------------------------------------------------------------
//Beginmain.
voidmain(void){
CHARszSource[100];
CHARszDestination[100];
CHARszPassword[100];
printf("Encryptafile.\n\n");
printf("Enterthenameofthefiletobeencrypted:");
scanf("%s",szSource);
printf("Enterthenameoftheoutputfile:");
scanf("%s",szDestination);
printf("Enterthepassword:");
scanf("%s",szPassword);
//--------------------------------------------------------------------
//CallEncryptFiletodotheactualencryption.
if(EncryptFile(szSource,szDestination,szPassword)){
printf("Encryptionofthefile%swasasuccess.\n",szSource);
printf("Theencrypteddataisinfile%s.\n",szDestination);
}else{
HandleError("Errorencryptingfile!");
}
}//Endofmain
//--------------------------------------------------------------------
//CodeforthefunctionEncryptFilecalledbymain.
staticBOOLEncryptFile(
PCHARszSource,
PCHARszDestination,
PCHARszPassword)
//--------------------------------------------------------------------
//Parameterspassedare:
//szSource,thenameoftheinput,aplaintextfile.
//szDestination,thenameoftheoutput,anencryptedfiletobe
//created.
//szPassword,thepassword.
{
//--------------------------------------------------------------------
//Declareandinitializelocalvariables.
FILE*hSource;
FILE*hDestination;
HCRYPTPROVhCryptProv;
HCRYPTKEYhKey;
HCRYPTHASHhHash;
PBYTEpbBuffer;
DWORDdwBlockLen;
DWORDdwBufferLen;
DWORDdwCount;
//--------------------------------------------------------------------
//Opensourcefile.
if(hSource=fopen(szSource,"rb")){
printf("Thesourceplaintextfile,%s,isopen.\n",szSource);
}else{
HandleError("Erroropeningsourceplaintextfile!");
}
//--------------------------------------------------------------------
//Opendestinationfile.
if(hDestination=fopen(szDestination,"wb")){
printf("Destinationfile%sisopen.\n",szDestination);
}else{
HandleError("Erroropeningdestinationciphertextfile!");
}
//以下获得一个CSP句柄
if(CryptAcquireContext(
&hCryptProv,
NULL,//NULL表示使用默认密钥容器,默认密钥容器名
//为用户登陆名
NULL,
PROV_RSA_FULL,
0)){
printf("Acryptographicproviderhasbeenacquired.\n");
}else{
if(CryptAcquireContext(
&hCryptProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_NEWKEYSET))//创建密钥容器
{
//创建密钥容器成功,并得到CSP句柄
printf("Anewkeycontainerhasbeencreated.\n");
}else{
HandleError("Couldnotcreateanewkeycontainer.\n");
}
}
//--------------------------------------------------------------------
//创建一个会话密钥(sessionkey)
//会话密钥也叫对称密钥,用于对称加密算法。
//(注:一个Session是指从调用函数CryptAcquireContext到调用函数
//CryptReleaseContext期间的阶段。会话密钥只能存在于一个会话过程)
//--------------------------------------------------------------------
//Createahashobject.
if(CryptCreateHash(
hCryptProv,
CALG_MD5,
0,
0,
&hHash)){
printf("Ahashobjecthasbeencreated.\n");
}else{
HandleError("ErrorduringCryptCreateHash!\n");
}
//--------------------------------------------------------------------
//用输入的密码产生一个散列
if(CryptHashData(
hHash,
(BYTE*)szPassword,
strlen(szPassword),
0)){
printf("Thepasswordhasbeenaddedtothehash.\n");
}else{
HandleError("ErrorduringCryptHashData.\n");
}
//--------------------------------------------------------------------
//通过散列生成会话密钥
if(CryptDeriveKey(
hCryptProv,
ENCRYPT_ALGORITHM,
hHash,
KEYLENGTH,
&hKey)){
printf("Anencryptionkeyisderivedfromthepasswordhash.\n");
}else{
HandleError("ErrorduringCryptDeriveKey!\n");
}
//--------------------------------------------------------------------
//Destroythehashobject.
CryptDestroyHash(hHash);
hHash=NULL;
//--------------------------------------------------------------------
//Thesessionkeyisnowready.
//--------------------------------------------------------------------
//因为加密算法是按ENCRYPT_BLOCK_SIZE大小的块加密的,所以被加密的
//数据长度必须是ENCRYPT_BLOCK_SIZE的整数倍。下面计算一次加密的
//数据长度。
dwBlockLen=1000-1000%ENCRYPT_BLOCK_SIZE;
//--------------------------------------------------------------------
//Determinetheblocksize.Ifablockcipherisused,
//itmusthaveroomforanextrablock.
if(ENCRYPT_BLOCK_SIZE>1)
dwBufferLen=dwBlockLen+ENCRYPT_BLOCK_SIZE;
else
dwBufferLen=dwBlockLen;
//--------------------------------------------------------------------
//Allocatememory.
if(pbBuffer=(BYTE*)malloc(dwBufferLen)){
printf("Memoryhasbeenallocatedforthebuffer.\n");
}else{
HandleError("Outofmemory.\n");
}
//--------------------------------------------------------------------
//Inadoloop,encryptthesourcefileandwritetothesourcefile.
do{
//--------------------------------------------------------------------
//ReaduptodwBlockLenbytesfromthesourcefile.
dwCount=fread(pbBuffer,1,dwBlockLen,hSource);
if(ferror(hSource)){
HandleError("Errorreadingplaintext!\n");
}
//--------------------------------------------------------------------
//加密数据
if(!CryptEncrypt(
hKey,//密钥
0,//如果数据同时进行散列和加密,这里传入一个
//散列对象
feof(hSource),//如果是最后一个被加密的块,输入TRUE.如果不是输.
//入FALSE这里通过判断是否到文件尾来决定是否为
//最后一块。
0,//保留
pbBuffer,//输入被加密数据,输出加密后的数据
&dwCount,//输入被加密数据实际长度,输出加密后数据长度
dwBufferLen))//pbBuffer的大小。
{
HandleError("ErrorduringCryptEncrypt.\n");
}
//--------------------------------------------------------------------
//Writedatatothedestinationfile.
fwrite(pbBuffer,1,dwCount,hDestination);
if(ferror(hDestination)){
HandleError("Errorwritingciphertext.");
}
}while(!feof(hSource));
//--------------------------------------------------------------------
//Endthedoloopwhenthelastblockofthesourcefilehasbeen
//read,encrypted,andwrittentothedestinationfile.
//--------------------------------------------------------------------
//Closefiles.
if(hSource)
fclose(hSource);
if(hDestination)
fclose(hDestination);
//--------------------------------------------------------------------
//Freememory.
if(pbBuffer)
free(pbBuffer);
//--------------------------------------------------------------------
//Destroysessionkey.
if(hKey)
CryptDestroyKey(hKey);
//--------------------------------------------------------------------
//Destroyhashobject.
if(hHash)
CryptDestroyHash(hHash);
//--------------------------------------------------------------------
//Releaseproviderhandle.
if(hCryptProv)
CryptReleaseContext(hCryptProv,0);
return(TRUE);
}//EndofEncryptfile
//--------------------------------------------------------------------
//ThisexampleusesthefunctionHandleError,asimpleerror
//handlingfunction,toprintanerrormessagetothestandarderror
//(stderr)fileandexittheprogram.
//Formostapplications,replacethisfunctionwithone
//thatdoesmoreextensiveerrorreporting.
voidHandleError(char*s){
fprintf(stderr,"Anerroroccurredinrunningtheprogram.\n");
fprintf(stderr,"%s\n",s);
fprintf(stderr,"Errornumber%x.\n",GetLastError());
fprintf(stderr,"Programterminating.\n");
exit(1);
}//EndofHandleError |