接着上一篇 将函数改改就可演变出解密版的 ,代码如下:
#include "stdafx.h"
#include "des.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string>
#include <stdio.h>
#pragma warning(disable:4996)
int FileSymEnc(const char *pfile1,const char *pfile2){
int ret = 0;
FILE *fp1 = NULL, *fp2 = NULL;
unsigned char plain[4096];
int plainlen = 0,plainlen2=0;
unsigned char cryptbuf[4096] = { 0 };
int cryptlen = 0;
fp1 = fopen(pfile1,"rb");
if (fp1 == NULL){
goto End;
}
fp2 = fopen(pfile2,"wb");
if (fp2 == NULL){
goto End;
}
//文件打开了,要拷贝数据了
while (!feof(fp1)){
plainlen=fread(plain, 1, 4096, fp1);
if (feof(fp1)){//读完数据以后,判断是否文件结束
break;
}
//加密==4K的数据
ret = DesEnc_raw(plain, plainlen, cryptbuf, &cryptlen);
if (ret != 0){
printf("func DesEnc() err:%d\n",ret);
goto End;
}
plainlen2 = fwrite(cryptbuf, 1, cryptlen, fp2);
if (plainlen2 != cryptlen){
ret = -3;
printf("写文件失败,请检查是否磁盘已满\n");
goto End;
}
}
//小于4k,就直接写
//加密
ret = DesEnc(plain,plainlen,cryptbuf,&cryptlen);
if (ret != 0){
printf("func DesEnc() err:%d\n", ret);
goto End;
}
plainlen2 = fwrite(cryptbuf, 1, cryptlen, fp2);
if (plainlen2 != cryptlen){
ret = -3;
printf("写文件失败,请检查是否磁盘已满\n");
goto End;
}
End:
if (fp1 != NULL)
{
fclose(fp1);
}
if (fp2 != NULL){
fclose(fp2);
}
return 0;
}
//解密
int FileSymDec(const char *pfile1, const char *pfile2){//pfile1密文,pfile2明文
int ret = 0;
FILE *fp1 = NULL, *fp2 = NULL;
unsigned char plain[4096];
int plainlen = 0, plainlen2 = 0;
unsigned char cryptbuf[4096] = { 0 };
int cryptlen = 0;
fp1 = fopen(pfile1, "rb");
if (fp1 == NULL){
goto End;
}
fp2 = fopen(pfile2, "wb");
if (fp2 == NULL){
goto End;
}
//文件打开了,要拷贝数据了
while (!feof(fp1)){
cryptlen = fread(cryptbuf, 1, 4096, fp1);
if (feof(fp1)){//读完数据以后,判断是否文件结束
break;
}
//解密==4K的数据
ret = DesDec_raw(cryptbuf, cryptlen, plain, &plainlen);
if (ret != 0){
printf("func DesDec() err:%d\n", ret);
goto End;
}
plainlen2 = fwrite(plain, 1, plainlen, fp2);
if (plainlen != cryptlen){
ret = -3;
printf("解密写文件失败\n");
goto End;
}
}
//小于4k,就直接写
//加密
ret = DesDec(cryptbuf, cryptlen, plain, &plainlen);
if (ret != 0){
printf("func DesDec() err:%d\n", ret);
goto End;
}
plainlen2 = fwrite(plain, 1, plainlen, fp2);
if (plainlen2 != plainlen){
ret = -3;
printf("解密时失败,请检查是否磁盘已满\n");
goto End;
}
End:
if (fp1 != NULL)
{
fclose(fp1);
}
if (fp2 != NULL){
fclose(fp2);
}
return 0;
}
void main(){
int ret = 0;
const char *file1 = "f:/normalBayes.txt";
const char *file2 = "f:/normalBayesenc.txt";
const char *file3 = "f:/normalBayesdec.txt";
ret = FileSymEnc(file1,file2);
ret = FileSymDec(file2,file3);
if (ret != 0){
printf("FileSymEnc err.\n");
}
return;
}