C++ File Encryption: AES Guide & Code
Symmetric encryption algorithms are commonly used for file encryption and decryption in C++, with AES (Advanced Encryption Standard) being the most popular. Here is a simple C++ code example demonstrating how to use the AES algorithm for file encryption and decryption:
#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;
}
In the example above, the encryptFile function is used to encrypt a file, and the decryptFile function is used to decrypt a file. It is important to note that the OpenSSL library needs to be installed and linked during compilation. Additionally, the same key should be used for both encrypting and decrypting the file.