C++でのファイルの暗号化と復号化の方法は何ですか?
C++でファイルの暗号化と複合化を行う場合、通常は対称暗号アルゴリズムを使用します。最も一般的に使用されるのはAES(Advanced Encryption Standard)アルゴリズムです。以下はAESアルゴリズムを使用してファイルを暗号化および複合化する方法を示す簡単なC++のコード例です。
#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ライブラリをインストールし、対応するライブラリファイルをコンパイル時にリンクする必要があることです。また、ファイルの暗号化と復号化の過程では、同じキーを使用する必要があります。