C语言解密程序如何将操作后的缓冲区数据写入新文件
代码核心问题排查
你当前的解密逻辑不生效、缓冲区内容未修改的问题,由3个典型错误导致:
- 循环遍历条件错误:
sizeof(buffer)获取的是指针变量本身的内存大小(64位系统为8字节、32位为4字节),并非你申请的缓冲区总长度,应该替换为读取到的文件实际大小lSize - 解密结果未回写缓冲区:
nibbleSwap和bitSwap都是值传递,返回的处理后结果没有赋值给对应位置的缓冲区元素,处理结果直接被丢弃,原缓冲区内容自然不会发生变化 - 输出文件名拼接越界:直接对
argv[1]指向的命令行参数字符串执行strncat追加后缀,会超出原字符串的预留内存空间,引发未定义行为,需要单独申请内存存储输出文件名
修改后可正常运行的完整代码
#include <stdio.h> #include <stdlib.h> #include <string.h> /*----------------------------------------- * 交换字节的高低四位 */ unsigned char nibbleSwap(unsigned char byte){ return ( (byte & 0x0f) << 4 | (byte & 0xf0) >> 4); } /*----------------------------------------- * 反转字节的所有位顺序 */ unsigned char bitSwap(unsigned char byte){ unsigned char b = nibbleSwap(byte); b = (b & 0xcc) >> 2 | (b & 0x33) << 2; b = (b & 0xaa) >> 1 | (b & 0x55) << 1; return b; } int main(int argc, char**argv){ FILE * pFile; char * outputFile; unsigned char * buffer; long lSize; size_t result; // 校验入参 if(argc < 2) { printf("请指定要解密的文件路径\n"); return -1; } printf("Author: Torin Costales \n"); printf("Input File: %s\n", argv[1]); // 打开输入文件 pFile = fopen(argv[1], "rb"); if(pFile == NULL){ printf("OPEN ERROR"); return -1; } // 获取文件大小 fseek (pFile, 0, SEEK_END); lSize = ftell(pFile); rewind (pFile); // 分配缓冲区内存 buffer = (unsigned char*) malloc (sizeof(unsigned char)*lSize); if(buffer == NULL) { printf("MEM ERROR"); fclose(pFile); return -1; } // 读取文件内容到缓冲区 result = fread(buffer, sizeof(unsigned char), lSize, pFile); if(result != lSize){ printf("Read error"); free(buffer); fclose(pFile); return -1; } // 输入文件读取完成提前关闭 fclose(pFile); // 解密逻辑:奇数下标字节交换高低四位,偶数下标字节反转位顺序 for(int x = 0; x < lSize; x++){ if(x % 2 == 1){ buffer[x] = nibbleSwap(buffer[x]); } else { buffer[x] = bitSwap(buffer[x]); } } // 生成输出文件名 outputFile = malloc(strlen(argv[1]) + 3); // 预留后缀.d和结束符的空间 strcpy(outputFile, argv[1]); strcat(outputFile, ".d"); // 写入输出文件 pFile = fopen(outputFile, "wb"); if(pFile == NULL) { printf("Output file open error"); free(buffer); free(outputFile); return -1; } printf("Output File: %s\n", outputFile); fwrite(buffer, sizeof(unsigned char), lSize, pFile); fclose(pFile); // 释放申请的内存避免泄漏 free(buffer); free(outputFile); return 0; }
内容的提问来源于stack exchange,提问作者Torin Costales
相关产品推荐
相关产品推荐

