写加密文件内容
2016-05-13 18:31 sylar_liang 阅读(221) 评论(0) 编辑 收藏 举报这个类写得很烂。 chBuffer 使用前要 memset 初始化一下,否则会报:
Run-Time Check Failure #2 - Stack around the variable '' was corrupted.
class EncryFile
{
public:
void CryptString(unsigned char chKey); //加、解密字符串
bool LoadStringFromFile(const CString &strFileName, unsigned char chKey); //读取解密
bool SaveStringToFile(const CString &strFileName, unsigned char chKey);//保存加密
public:
CString m_strFileName; //文件名
CString m_strFileBuffer; //文件缓冲区
DWORD m_dwFileLength; //文件长度
TCHAR chBuffer[MAX_SIZE]; 文件缓冲区//#define MAX_SIZE 65535
};
//.cpp
const unsigned char DEFAULT = 123;
void CryptString(unsgined char chKey)
{
DWORD dwLen = m_strFileBuffer.Getlength();
for(DWORD i =0; i<dwLen; i++)
{
chBuffer[i] = chBuffer[i]^chKey; //异或,j加密
}
m_strFileBuffer = chBuffer;
}
bool LoadStringFromFile(const CString &strFileName, unsigned char chKey)
{
DWORD dwRead = 0;
HANDLE hFile = CreateFile(strFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE != hFile)
{
//打开成功
m_dwFileLength = GetFileSize(hFile, NULL);
if ( !ReadFile(hFile, chBuffer, m_dwFileLength, &dwRead, NULL) )
{
//error
return false;
}
CloseHandle(hFile); //关闭文件句柄
}
else
{
//error : open fail.
return false;
}
m_strFileBuffer = chBuffer; //
CryptString(chKey); //解密
//测试读出来的文件内容
hFile = CreateFile("xxx.ini", GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
BOOL bRet = (::WriteFile(hFile, m_strFileBuffer, m_dwFileLength, &dwRead, NULL));
if (bRet)
{
CloseHandle(hFile);
return true;
}
return false;
}
bool SaveStringToFile(const Cstring &strFileName, unsigned char chKey)
{
DWORD dwRead = 0;
HANDLE hFile = CreateFile(strFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
if (INVALID_HANDLE_VALUE != hFile)
{
m_dwFileLength = GetFileSize(hFile, NULL);
if (!ReadFile(hFile, chBuffer, m_dwFileLength, &dwRead, NULL) )
{
//error read
return false;
}
Closehandle(hFile);
}
else
{
//open error
return false;
}
m_strFileBuffer = chBuffer;
CryptString(chKey); //加密
hFile = CreateFile(strFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(INVALID_HANDLE_VALUE != hFile)
{
DWROD dwWrite = 0;
if (!WriteFile(hFile, m_strFileBuffer, m_dwFileLenght, &dwWrite, NULL))
{//erro write return false;}
Closehanle(hFile);
}
else
{//error open return false}
CryptString(chKey); //对字符串解密是为了不改变原字符串
return true;
}