如何在写入文件之前对结构进行编码/加密
how to encode/encrypt a structure before write to file
我有一个这样的结构体:
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);
}
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 如何确定我已使用非编码文件到达 EOF?
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 确定输入"conscalc: calc"的类型时出错。不能联合编码器。具有不同字段集的结构类型
- 配置 AVCodecContext 结构以从原始 PCM 编码到 u-law
- 试图在编码问题中理解此结构而迷失
- 使用 UDP 协议从 Windows 套接字发送到 Qt 套接字的网络数据包上的结构编码和解码
- 游戏引擎:如何从结构:编码实践转换变量
- c++如何从硬编码结构中获取数据
- 将DER编码的X509证书缓冲区转换为Windows cert_context结构
- 如何在C++中编码大型复杂、恒定的数据结构
- 如何在写入文件之前对结构进行编码/加密
- 面试编码-将指向节点结构的指针作为参数,并返回传入数据结构的完整副本
- 基于TLV编码对数据结构进行编码
- 使用数组结构的c++消息编码器