如何在写入文件之前对结构进行编码/加密

how to encode/encrypt a structure before write to file

本文关键字:结构 编码 加密 文件      更新时间:2023-10-16

我有一个这样的结构体:

struct ITEM
{
    INT         ItemNum;
    BYTE        Kind;
    char        ItemName[200];
};

我把ITEM结构写进文件,没有像这样编码,没有问题。

ez_map<INT, ITEM>::iterator itrItem = mapItem.begin();
while (itrItem != mapItem.end())
{
   ITEM *pItem = &itrItem->second;
   WriteFile(hFile, (LPCVOID)pItem, sizeof(ITEM), &dwBytesWritten, NULL);
}

我尝试将结构转换为字节数组,然后编码该数组并复制回结构,如下所示:

ez_map<INT, ITEM>::iterator itrItem = mapItem.begin();
while (itrItem != mapItem.end())
{
   ITEM *pItem = &itrItem->second;
   //begin to encode
   BYTE bytesArr[sizeof(ITEM)];
   memcpy(bytesArr, &pItem, sizeof(ITEM));
   for(int i = 0; i < sizeof(ITEM); i++){
      bytesArr[i] ^= 1;
   }
   memcpy(&pItem, bytesArr, sizeof(ITEM)); //crash here, because NULL character was xorred.
   //end encode
   WriteFile(hFile, (LPCVOID)pItem, sizeof(ITEM), &dwBytesWritten, NULL);
}

我也尝试使用CryptEncrypt, &pItem作为pbData, sizeof(ITEM)作为pdwDataLen,但没有运气。
如果你能帮助我,谢谢你。

问题是第二个memcpy()上的&pItem。您正在复制到错误的目标内存地址。它应该是这样的:

memcpy(pItem, bytesArr, sizeof(ITEM));
然而,这第二个额外的副本是不需要的。您可以使用这样的代码:
while (itrItem != mapItem.end())
{
   ITEM *pItem = &itrItem->second;
   //begin to encode
   BYTE* pb = (BYTE*)pItem;
   int n = sizeof(ITEM);
   do *pb++ ^= 1; while (--n);
   //end encode
   WriteFile(hFile, pItem, sizeof(ITEM), &dwBytesWritten, NULL);
   // may be decode Item here if need
}

或者,如果pItem必须为只读:

while (itrItem != mapItem.end())
{
   ITEM *pItem = &itrItem->second;
   //begin to encode
   BYTE bytesArr[sizeof(ITEM)], *pc = bytesArr, *pb = (BYTE*)pItem;
   int n = sizeof(ITEM);
   do *pc++ = *pb++ ^ 1; while (--n);
   //end encode
   WriteFile(hFile, bytesArr, sizeof(ITEM), &dwBytesWritten, NULL);
}