c++文件加密解密怎么实现

   2025-02-15 3820
核心提示:在C++中,可以使用一些加密算法来实现文件加密和解密。一种常见的加密算法是AES (Advanced Encryption Standard)。以下是一个使

在C++中,可以使用一些加密算法来实现文件加密和解密。

一种常见的加密算法是AES (Advanced Encryption Standard)。以下是一个使用AES算法对文件进行加密和解密的示例代码:

#include <iostream>#include <fstream>#include <string>#include <openssl/aes.h>const int AES_KEY_LENGTH = 128; // 使用128位的AES加密std::string encryptFile(const std::string& inputFile, const std::string& outputFile, const std::string& key) {    std::ifstream fin(inputFile, std::ios::binary);    std::ofstream fout(outputFile, std::ios::binary);    // 设置AES加密密钥    AES_KEY aesKey;    AES_set_encrypt_key((const unsigned char*)key.c_str(), AES_KEY_LENGTH, &aesKey);    // 加密文件    unsigned char inBuffer[AES_BLOCK_SIZE];    unsigned char outBuffer[AES_BLOCK_SIZE];    while (fin.read((char*)inBuffer, AES_BLOCK_SIZE)) {        AES_encrypt(inBuffer, outBuffer, &aesKey);        fout.write((char*)outBuffer, AES_BLOCK_SIZE);    }    fin.close();    fout.close();    return outputFile;}std::string decryptFile(const std::string& inputFile, const std::string& outputFile, const std::string& key) {    std::ifstream fin(inputFile, std::ios::binary);    std::ofstream fout(outputFile, std::ios::binary);    // 设置AES解密密钥    AES_KEY aesKey;    AES_set_decrypt_key((const unsigned char*)key.c_str(), AES_KEY_LENGTH, &aesKey);    // 解密文件    unsigned char inBuffer[AES_BLOCK_SIZE];    unsigned char outBuffer[AES_BLOCK_SIZE];    while (fin.read((char*)inBuffer, AES_BLOCK_SIZE)) {        AES_decrypt(inBuffer, outBuffer, &aesKey);        fout.write((char*)outBuffer, AES_BLOCK_SIZE);    }    fin.close();    fout.close();    return outputFile;}int main() {    std::string inputFile = "input.txt";    std::string encryptedFile = "encrypted.txt";    std::string decryptedFile = "decrypted.txt";    std::string key = "mykey1234567890"; // 密钥    encryptFile(inputFile, encryptedFile, key);    decryptFile(encryptedFile, decryptedFile, key);    return 0;}

上述代码使用OpenSSL库中的AES函数。encryptFile函数接收输入文件路径、输出文件路径和密钥作为参数,将输入文件内容加密后写入输出文件。decryptFile函数接收加密后的文件路径、解密后的文件路径和密钥作为参数,将加密文件内容解密后写入解密后的文件。

请注意,这只是一个简单的示例代码,仅用于演示AES加密和解密。在实际应用中,需要考虑更多的安全性问题,如密钥的生成和存储、加密模式的选择等。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言