MFC中对文件base64加解密
/**
- 获取文件大小
- @param path 文件路径
*/
unsigned long myTools::get_file_size(const char *path)
{
unsigned long filesize = 0;
FILE *fp;
fp = fopen(path, “r+”);
if(fp == NULL)
return filesize;
fseek(fp, 0L, SEEK_END);
filesize = ftell(fp);
fclose(fp);
return filesize;
}
/**
- 删除单个字符
- @param str 输入字符串 c 需要删除的字符
*/
void myTools::delchar( char *str, char c ) //删除指定字符
{
int count = 0;
int i,j;
for(i=j=0;str[i]!=‘\0’;i++)
{
if(str[i]!=c)//判断是否有和待删除字符一样的字符
{
str[j++]=str[i];
}
if(str[i] ==’ ‘){
printf(“delete space!\n”);
}
if(str[i] == ‘\n’){
printf(“delete n !\n”);
}
}
str[j]=’\0’;//字符串结束
}
/**
-
对文件base64加密
-
@param filename 文件名 out_data 输出字符串
*/
int myTools::file_base64(const char *filename, char *out_data)
{
unsigned long fileSize = get_file_size(filename);
if (fileSize <= 0)
return 0;fprintf(stderr,“the data size=%d\n”,fileSize);
FILE* fp = fopen(filename, “rb”);
char* inBuffer = new char[fileSize];
ULONG uReaded = fread(inBuffer, 1, fileSize, fp);const BYTE* pbBinary = (const BYTE*)inBuffer;
DWORD dwLen;
CryptBinaryToStringA(pbBinary, fileSize, CRYPT_STRING_BASE64, NULL, &dwLen); //把二进制序列转换成字符串char* pCrypt1 = new char[dwLen];
CryptBinaryToStringA(pbBinary, fileSize, CRYPT_STRING_BASE64, pCrypt1, &dwLen);//把二进制序列转换成字符串
fclose(fp);delchar(pCrypt1, ‘\n’);
delchar(pCrypt1, ‘\r’);
strcpy(out_data, pCrypt1);
if (inBuffer)
{
delete[] inBuffer;
inBuffer = NULL;
}
if (pCrypt1)
{
delete[] pCrypt1;
pCrypt1 = NULL;
}
return 0;
}
/**
-
对base64数据流解码写入文件
-
@param data 输入数据流 len 输入数据长度 url写入文件名
*/
int myTools::base64_file(char *data,int len,char *url)
{
if(data==NULL)
{
return -1;
}
DWORD cbBinary;
DWORD dwSkip;
DWORD dwFlags;
CryptStringToBinaryA(data, len+1, CRYPT_STRING_BASE64, NULL, &cbBinary, &dwSkip, &dwFlags);BYTE* outBuffer = new BYTE[cbBinary];
CryptStringToBinaryA(data, len+1, CRYPT_STRING_BASE64, outBuffer, &cbBinary, &dwSkip, &dwFlags);FILE* fp = fopen(url, “wb”);
ULONG uWrite = fwrite(outBuffer, 1, cbBinary, fp);fclose(fp);
if (outBuffer)
{
delete[] outBuffer;
outBuffer = NULL;
}
return 0;
}