学堂 学堂 学堂公众号手机端

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

lewis 2年前 (2023-10-28) 阅读数 8 #技术

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

#include<iostream> #include<fstream> #include<openssl/aes.h> #include<openssl/rand.h> voidencryptFile(conststd::string&inputFile,conststd::string&outputFile,conststd::string&key){ AES_KEYaesKey; AES_set_encrypt_key((unsignedchar*)key.c_str(),128,&aesKey); std::ifstreamin(inputFile,std::ios::binary); std::ofstreamout(outputFile,std::ios::binary); unsignedchariv[AES_BLOCK_SIZE]; RAND_bytes(iv,AES_BLOCK_SIZE); out.write(reinterpret_cast<constchar*>(iv),AES_BLOCK_SIZE); unsignedcharinBuffer[AES_BLOCK_SIZE]; unsignedcharoutBuffer[AES_BLOCK_SIZE]; intnumBytesRead=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(); } voiddecryptFile(conststd::string&inputFile,conststd::string&outputFile,conststd::string&key){ AES_KEYaesKey; AES_set_decrypt_key((unsignedchar*)key.c_str(),128,&aesKey); std::ifstreamin(inputFile,std::ios::binary); std::ofstreamout(outputFile,std::ios::binary); unsignedchariv[AES_BLOCK_SIZE]; in.read(reinterpret_cast<char*>(iv),AES_BLOCK_SIZE); unsignedcharinBuffer[AES_BLOCK_SIZE]; unsignedcharoutBuffer[AES_BLOCK_SIZE]; intnumBytesRead=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(); } intmain(){ std::stringinputFile="plaintext.txt"; std::stringencryptedFile="encrypted.bin"; std::stringdecryptedFile="decrypted.txt"; std::stringkey="mysecretkey"; encryptFile(inputFile,encryptedFile,key); decryptFile(encryptedFile,decryptedFile,key); return0; }

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


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门