以下是一个实现上述功能的C++程序的源代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

void encryptFile(const string& filePath) {
    ifstream inputFile(filePath, ios::binary);
    if (!inputFile) {
        cerr << "Error: Unable to open file " << filePath << endl;
        return;
    }

    // 读取文件内容
    string content((istreambuf_iterator<char>(inputFile)), (istreambuf_iterator<char>()));
    inputFile.close();

    // 对文件内容进行加密
    for (char& c : content) {
        c = ~(c ^ 0xFF);
    }

    // 写入加密后的内容
    ofstream outputFile(filePath, ios::binary);
    if (!outputFile) {
        cerr << "Error: Unable to write to file " << filePath << endl;
        return;
    }
    outputFile << content;
    outputFile.close();

    cout << "File encrypted successfully." << endl;
}

void decryptFile(const string& filePath) {
    ifstream inputFile(filePath, ios::binary);
    if (!inputFile) {
        cerr << "Error: Unable to open file " << filePath << endl;
        return;
    }

    // 读取文件内容
    string content((istreambuf_iterator<char>(inputFile)), (istreambuf_iterator<char>()));
    inputFile.close();

    // 对文件内容进行解密
    for (char& c : content) {
        c = ~(c ^ 0xFF);
    }

    // 写入解密后的内容
    ofstream outputFile(filePath, ios::binary);
    if (!outputFile) {
        cerr << "Error: Unable to write to file " << filePath << endl;
        return;
    }
    outputFile << content;
    outputFile.close();

    cout << "File decrypted successfully." << endl;
}

int main() {
    string filePath = "path/to/your/file.pdf";
    string encryptedFilePath = "path/to/your/encrypted/file.pdf";

    ifstream checkFile(filePath);
    
    // 检查文件是否已加密
    if (checkFile && checkFile.peek() != ifstream::traits_type::eof()) {
        checkFile.close();
        decryptFile(filePath);  // 解密文件
    } else {
        checkFile.close();
        encryptFile(filePath);  // 加密文件
        remove(filePath.c_str());  // 删除原文件
        rename(encryptedFilePath.c_str(), filePath.c_str());  // 重命名加密后的文件
    }

    return 0;
}

请注意,这仅是一个基本的加密/解密程序,它只是对文件内容进行简单的位运算操作来实现加密和解密。对于真正的加密需求,需要使用更强大的加密算法和密钥管理。此代码仅供参考,不适用于真实加密应用


原文地址: http://www.cveoy.top/t/topic/iVba 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录