C++ 文件的加密与解密

思路:对文件的每个字节进行异或运算之后得到新的文件就是加密的,反之就是解密

加密

/**
 文件加密:使用密码加密
 */
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(){
    string filePath = "/Users/aaa/Documents/C++File/a.jpg";
    string fileEncodePath = "/Users/aaa/Documents/C++File/a_encode.jpg";
    
    FILE* file = fopen(filePath.data(), "rb");//以读取的模式打开文件
    FILE* fileEncode = fopen(fileEncodePath.data(), "wb");
    if (!file) {
        printf("%s文件路径错误\n",filePath.data());
        exit(0);
    }
    
    int a;
    //文件在解密时必须与此密码一致
    char password[] = "123456abcd23";
    int index = 0;
    while ((a = fgetc(file))!= EOF) {
        char item = password[index%strlen(password)];
        //单个字节 异或 之后存入新文件中
        fputc(a^item, fileEncode);
        index++;
    }
    fclose(file);
    fclose(fileEncode);
    return 0;
 }

解密

/**
 文件解密
 */
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

int main(){
    string filePath = "/Users/aaa/Documents/C++File/a_encode.jpg";
    string fileDecodePath = "/Users/aaa/Documents/C++File/a_decode.jpg";
    
    FILE* file = fopen(filePath.data(), "rb");//以读取的模式打开文件
    FILE* fileDecode = fopen(fileDecodePath.data(), "wb");
    if (!file) {
        printf("%s文件路径错误\n",filePath.data());
        exit(0);
    }
    
    int a ;
    //和上面加密时的密钥一致
    char password[] = "123456abcd23";
    int index = 0;
    int len = strlen(password);
    while ((a=fgetc(file))!=EOF) {
        char item = password[index%len];
        fputc(a^item, fileDecode);
        index++ ;
    }
    
    fclose(file);
    fclose(fileDecode);
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容