이 프로그램은 암호화와 암호 해독의 두 가지 옵션을 제공합니다. 기본 XOR 암호를 사용하여 사용자가 제공한 키를 사용하여 지정된 입력 및 출력 파일에 대한 암호화 및 복호화 작업을 수행합니다.
이 예제에서는 교육 목적으로 간단한 XOR 암호를 사용합니다. 실제로는 안전한 파일 암호화를 위해 더 고급 암호화 알고리즘을 사용해야 합니다.
소스코드
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Function to perform XOR encryption/decryption
void xorCipher(ifstream& inFile, ofstream& outFile, const string& key) {
char byte;
size_t keyIndex = 0;
while (inFile.get(byte)) {
byte ^= key[keyIndex];
outFile.put(byte);
keyIndex++;
if (keyIndex == key.length()) {
keyIndex = 0;
}
}
}
int main() {
string inputFileName, outputFileName, key;
int choice;
cout << "File Encryption/Decryption" << endl;
cout << "1. Encrypt a file" << endl;
cout << "2. Decrypt a file" << endl;
cout << "Enter your choice (1/2): ";
cin >> choice;
if (choice != 1 && choice != 2) {
cout << "Invalid choice. Please choose 1 for encryption or 2 for decryption." << endl;
return 1; // Exit with an error code
}
cout << "Enter input file name: ";
cin >> inputFileName;
cout << "Enter output file name: ";
cin >> outputFileName;
cout << "Enter encryption/decryption key: ";
cin >> key;
ifstream inFile(inputFileName, ios::binary);
ofstream outFile(outputFileName, ios::binary);
if (!inFile) {
cout << "Error opening input file." << endl;
return 1; // Exit with an error code
}
if (!outFile) {
cout << "Error opening output file." << endl;
return 1; // Exit with an error code
}
if (choice == 1) {
xorCipher(inFile, outFile, key);
cout << "File encrypted successfully." << endl;
} else {
xorCipher(inFile, outFile, key);
cout << "File decrypted successfully." << endl;
}
inFile.close();
outFile.close();
return 0; // Exit successfully
}
결과
File Encryption/Decryption
1. Encrypt a file
2. Decrypt a file
Enter your choice (1/2): 1
Enter input file name: input.txt
Enter output file name: encrypted.txt
Enter encryption/decryption key: mykey
File encrypted successfully.
이 예에서는 사용자가 암호화 옵션 1을 선택했습니다. 프로그램은 입력 파일 이름(예: input.txt), 출력 파일 이름(예: encrypted.txt), 암호화/암호 해독 키(예: mykey)를 입력하라는 메시지를 표시합니다. 암호화 후에는 "File encrypted successfully."라는 메시지가 표시됩니다.
복호화(옵션 2)의 경우 프로세스는 비슷하지만 동일한 키를 사용하여 파일을 복호화하고 성공하면 "File decrypted successfully."라는 메시지를 표시합니다.
'Programming language > C++' 카테고리의 다른 글
[C++] 틱택토 게임 구현 (1) | 2023.10.06 |
---|---|
[C++]미로 생성기 & 미로 풀이 도구 만들기 (1) | 2023.10.06 |
[C++] 소수 판별 프로그램 (0) | 2023.10.06 |
[C++] palindrome 예제 소스코드 (0) | 2023.10.06 |
[C++] 환율 계산 프로그램 (0) | 2023.10.06 |