#include <stdio.h>
// 移位加密函数
void encryptFile(const char* inputPath, const char* outputPath, int key) {
FILE* inputFile = fopen(inputPath, "rb");
FILE* outputFile = fopen(outputPath, "wb");
char buffer[1024]; // 定义一个缓冲区用于读取和写入数据块
size_t bytesRead;
while (1) {
bytesRead = fread(buffer, sizeof(char), sizeof(buffer), inputFile);
if (bytesRead <= 0) {
break; // 读取结束或发生错误
}
for (size_t i = 0; i < bytesRead; i++) {
buffer[i] = buffer[i] + key; // 使用加法进行移位加密
if (buffer[i] > 127) { // 处理溢出情况,确保仍在ASCII码范围内
buffer[i] = buffer[i] - 128;
}
}
fwrite(buffer, sizeof(char), bytesRead, outputFile); // 将加密后的数据块写入输出文件
}
fclose(inputFile);
fclose(outputFile);
}
// 移位解密函数
void decryptFile(const char* inputPath, const char* outputPath, int key) {
encryptFile(inputPath, outputPath, -key); // 解密与加密使用相同的操作,但使用负的移位数
}
int main() {
const char* inputFilePath = "input.txt";
const char* encryptedFilePath = "encrypted.txt";
const char* decryptedFilePath = "decrypted.txt";
int shiftKey = 200; // 移位加密所使用的密钥
// 加密文件
encryptFile(inputFilePath, encryptedFilePath, shiftKey);
// 解密文件
decryptFile(encryptedFilePath, decryptedFilePath, shiftKey);
return 0;
}
c语言移位加解密
最新推荐文章于 2024-04-12 07:24:34 发布