C++ 文件的加密與解密

思路:對(duì)文件的每個(gè)字節(jié)進(jìn)行異或運(yùn)算之后得到新的文件就是加密的,反之就是解密

加密

/**
 文件加密:使用密碼加密
 */
#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文件路徑錯(cuò)誤\n",filePath.data());
        exit(0);
    }
    
    int a;
    //文件在解密時(shí)必須與此密碼一致
    char password[] = "123456abcd23";
    int index = 0;
    while ((a = fgetc(file))!= EOF) {
        char item = password[index%strlen(password)];
        //單個(gè)字節(jié) 異或 之后存入新文件中
        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文件路徑錯(cuò)誤\n",filePath.data());
        exit(0);
    }
    
    int a ;
    //和上面加密時(shí)的密鑰一致
    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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容