当前位置: 首页 > 建站教程

c++文件加密解密的方法是什么

时间:2026-02-01 13:23:51

在C++中进行文件加密和解密通常采用对称加密算法,其中最常用的是AES(Advanced Encryption Standard)算法。以下是一个简单的C++代码示例,演示如何使用AES算法进行文件加密和解密:

#include <iostream>#include <fstream>#include <openssl/aes.h>#include <openssl/rand.h>void encryptFile(const std::string& inputFile, const std::string& outputFile, const std::string& key) {AES_KEY aesKey;AES_set_encrypt_key((unsigned char*)key.c_str(), 128, &aesKey);std::ifstream in(inputFile, std::ios::binary);std::ofstream out(outputFile, std::ios::binary);unsigned char iv[AES_BLOCK_SIZE];RAND_bytes(iv, AES_BLOCK_SIZE);out.write(reinterpret_cast<const char*>(iv), AES_BLOCK_SIZE);unsigned char inBuffer[AES_BLOCK_SIZE];unsigned char outBuffer[AES_BLOCK_SIZE];int numBytesRead = 0;while (in.read(reinterpret_cast<char*>(inBuffer), AES_BLOCK_SIZE)) {AES_cbc_encrypt(inBuffer, outBuffer, AES_BLOCK_SIZE, &aesKey, iv, AES_ENCRYPT);out.write(reinterpret_cast<char*>(outBuffer), AES_BLOCK_SIZE);numBytesRead += AES_BLOCK_SIZE;}in.close();out.close();}void decryptFile(const std::string& inputFile, const std::string& outputFile, const std::string& key) {AES_KEY aesKey;AES_set_decrypt_key((unsigned char*)key.c_str(), 128, &aesKey);std::ifstream in(inputFile, std::ios::binary);std::ofstream out(outputFile, std::ios::binary);unsigned char iv[AES_BLOCK_SIZE];in.read(reinterpret_cast<char*>(iv), AES_BLOCK_SIZE);unsigned char inBuffer[AES_BLOCK_SIZE];unsigned char outBuffer[AES_BLOCK_SIZE];int numBytesRead = 0;while (in.read(reinterpret_cast<char*>(inBuffer), AES_BLOCK_SIZE)) {AES_cbc_encrypt(inBuffer, outBuffer, AES_BLOCK_SIZE, &aesKey, iv, AES_DECRYPT);out.write(reinterpret_cast<char*>(outBuffer), AES_BLOCK_SIZE);numBytesRead += AES_BLOCK_SIZE;}in.close();out.close();}int main() {std::string inputFile = "plaintext.txt";std::string encryptedFile = "encrypted.bin";std::string decryptedFile = "decrypted.txt";std::string key = "mysecretkey";encryptFile(inputFile, encryptedFile, key);decryptFile(encryptedFile, decryptedFile, key);return 0;}

在上面的示例中,encryptFile函数用于加密文件,decryptFile函数用于解密文件。需要注意的是,需要安装OpenSSL库,并在编译时链接对应的库文件。此外,文件加密和解密的过程中需要使用相同的密钥。


上一篇:php中goto的功能有哪些
下一篇:linux perl命令安装的方法是什么
C++
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素