码迷,mamicode.com
首页 > 其他好文 > 详细

写加密文件内容

时间:2016-05-13 19:08:39      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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;

}

 

写加密文件内容

标签:

原文地址:http://www.cnblogs.com/sylar-liang/p/5490615.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!