[c++] C++에서의 파일 암호화

파일 암호화는 데이터 보안을 강화하기 위해 사용되는 기술로, 민감한 정보가 포함된 파일을 안전하게 보호하는 데 사용됩니다. C++를 사용하여 파일을 암호화하고 복호화하는 방법을 살펴보겠습니다.

1. 파일 암호화 방법

C++를 사용하여 파일을 암호화하는 가장 흔한 방법은 대칭키 알고리즘인 AES (Advanced Encryption Standard)를 이용하는 것입니다. 이 알고리즘은 안전하고 효율적이며, C++에서도 강력한 보안을 제공합니다.

아래는 C++에서 파일을 AES로 암호화하는 방법에 대한 간단한 예제 코드입니다.

#include <iostream>
#include <fstream>
#include <openssl/aes.h>
#include <openssl/rand.h>

void encryptFile(const char* inputFile, const char* outputFile, const unsigned char* key) {
    // 파일 읽기
    std::ifstream in(inputFile, std::ios::binary);
    std::ofstream out(outputFile, std::ios::binary);

    // AES 알고리즘 초기화
    AES_KEY aesKey;
    AES_set_encrypt_key(key, 256, &aesKey);

    unsigned char iv[AES_BLOCK_SIZE];
    RAND_bytes(iv, AES_BLOCK_SIZE);
    out.write(reinterpret_cast<char*>(iv), AES_BLOCK_SIZE);

    // 암호화
    unsigned char indata[AES_BLOCK_SIZE];
    unsigned char outdata[AES_BLOCK_SIZE];
    while(in.read(reinterpret_cast<char*>(indata), AES_BLOCK_SIZE)) {
        AES_cbc_encrypt(indata, outdata, AES_BLOCK_SIZE, &aesKey, iv, AES_ENCRYPT);
        out.write(reinterpret_cast<char*>(outdata), AES_BLOCK_SIZE);
    }
}

int main() {
    const char* inputFile = "plain.txt";
    const char* outputFile = "encrypted.txt";
    const unsigned char key[] = "0123456789abcdef";

    encryptFile(inputFile, outputFile, key);

    return 0;
}

이 예제는 OpenSSL 라이브러리를 사용하여 AES를 구현하였으며, ‘plain.txt’ 파일을 ‘encrypted.txt’로 암호화합니다.

2. 파일 복호화 방법

복호화는 암호화된 파일을 원래의 형태로 디코딩하는 프로세스입니다. C++를 사용하여 파일을 복호화하는 예제 코드는 다음과 같습니다.

void decryptFile(const char* inputFile, const char* outputFile, const unsigned char* key) {
    std::ifstream in(inputFile, std::ios::binary);
    std::ofstream out(outputFile, std::ios::binary);

    AES_KEY aesKey;
    AES_set_decrypt_key(key, 256, &aesKey);

    unsigned char iv[AES_BLOCK_SIZE];
    in.read(reinterpret_cast<char*>(iv), AES_BLOCK_SIZE);

    unsigned char indata[AES_BLOCK_SIZE];
    unsigned char outdata[AES_BLOCK_SIZE];
    while(in.read(reinterpret_cast<char*>(indata), AES_BLOCK_SIZE)) {
        AES_cbc_encrypt(indata, outdata, AES_BLOCK_SIZE, &aesKey, iv, AES_DECRYPT);
        out.write(reinterpret_cast<char*>(outdata), AES_BLOCK_SIZE);
    }
}

int main() {
    const char* inputFile = "encrypted.txt";
    const char* outputFile = "decrypted.txt";
    const unsigned char key[] = "0123456789abcdef";

    decryptFile(inputFile, outputFile, key);

    return 0;
}

위 코드는 앞서 암호화한 ‘encrypted.txt’ 파일을 ‘decrypted.txt’로 복호화하는 예제를 보여줍니다.

마치며

파일 암호화는 보안을 강화하고 개인 정보를 안전하게 유지하기 위한 중요한 방법 중 하나입니다. 이 문서에서는 C++를 사용하여 파일을 AES 알고리즘을 이용해 암호화하고 복호화하는 방법에 대해 설명했습니다. 파일 암호화에 대한 더 많은 내용은 OpenSSL 라이브러리 문서 등을 참고하시기 바랍니다.

참고 문헌:

이렇게 C++를 이용하여 파일을 암호화 및 복호화하는 방법에 대해 알아보았습니다.