파일의 암호화/복호화? (Encryption/ Decryption of a file?)


문제 설명

파일의 암호화/복호화? (Encryption/ Decryption of a file?)

I am trying to encrypt, then decrypt the file. When I try the decryption the file, I would like to display the content on the screen to make sure that the process of decryption is done without problems. But, I don't have any display of the decryption of the file. I am not sure what is missing in my code. I am using Dev_C++. Your help will be very appreciated. The code is below.

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>



using namespace std;


int main()
{ 
    string line;

    string file, encrfile;
    int i, key_length, longueur;
    unsigned int key=0;
    char ch[100];

    cout<<"enter a secret key: ";
    cin.getline(ch, 100);

    for (i=0;ch[i];i++)
    key=(key+3)*ch[i];

    cout<<"Password generated: "<<key;

    cout<<"\n\nEnter the name of the input file: ";
    getline(cin,file);

    cout<<"\nEnter the name of the output file: ";
    getline(cin,encrfile);

    ifstream IS;
    IS.open(file.c_str() );  
    ofstream OS;
    OS.open(encrfile.c_str());

    while(IS>>line);
    {

        //encrypting each character
        for (i=0;i<line.length();i++)
        {
            line[i]^=rand()>>8;
            OS<<line[i];  //writing the character in the output file            
        }
    }

    IS.close();
    OS.close(); 

    cout<<"File "<<encrfile<<" has been encrypted"<<endl;

    cout<<"\nEnter the name of the file to decrypt: ";
    getline(cin,encrfile);  

    cout<<"\n\nDecryption of file:  "<<endl;
    ifstream IS2;
    IS2.open(encrfile.c_str()); 

    while(IS2>>line);
    {

        for (i=0;i<line.length();i++)
        {
            line[i]^=rand()>>8;
            cout<<line[i];
       }
    }
    IS2.close();



return 0;

}


참조 솔루션

방법 1:

The ; means the loop has an empty body. So you read the whole file word by word here.

while(IS>>line);

So correcting the above to: Now you are reading a word at a time. But it is dropping the spaces between words.

while(IS>>line)

This should work more as you expect it.  

while(std::getline(IS, line))

But here you are discarding the new line character. So again this is probably not what you want. The point of encryption is to preserve all the characters.

To get all the characters the easiest is to read them one by one:

char c;
while(IS >> std::noskipws >> c)

Use std::noskipws (so you don't loose any characters).

You are encrypting using a rand number. Fine: But you may want to seed the random number generator with the key to make sure you get the same sequence of rands each time. But this will only work for a very specific OS/Lib combination. 

        line[i]^=rand()>>8;

Alternatively you can replace rand() with key.

        line[i]^=key>>8;

Same problem as above

while(IS2>>line);

Same problem as above

        line[i]^=rand()>>8;

Using rand() as the encryption key:

Not tested: But should be a starting point:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

int main()
{ 
    std::cout<<"enter a secret key: ";
    std::string ch; 
    std::getline(std::cin,ch);
    unsigned int key = 0;

    for (int i=0;i < ch.size();i++)
        key=(key+3)*ch[i];

    std::cout << "Password generated: "<<key << "\n"
              << "\nEnter the name of the input file:\n";

    std::string file;
    std::getline(std::cin,file);
    std::ifstream IS(file.c_str());  

    std::cout<<"Enter the name of the output file:\n";
    std::string encrfile;
    std::getline(std::cin,encrfile);
    std::ofstream OS(encrfile.c_str());

    std::string line;

    char c;

    srand(key);  // Reset the random number sequence.
    while(IS >> std::noskipws >> c)
    {   
        c ^= (rand() >> 8); 
        OS << c;
    }   
    IS.close();
    OS.close();

    std::cout << "File " << encrfile << " has been encrypted\n"
              << "Enter the name of the file to decrypt:\n";

    std::getline(std::cin,encrfile);
    std::cout<<"\nDecryption of file:\n";

    std::ifstream IS2(encrfile.c_str());

    srand(key);  // Reset the random number sequence.
    while(IS >> std::noskipws >> c)
    {
        c ^= (rand()>>8);
        std::cout << c;
    }
    IS2.close();
}

(by T4000Martin York)

참조 문서

  1. Encryption/ Decryption of a file? (CC BY‑SA 3.0/4.0)

#C++ #Encryption #file






관련 질문

파일의 암호화/복호화? (Encryption/ Decryption of a file?)

이상한 범위 확인 연산자가 있는 C++ typedef (C++ typedef with strange scope resolution operator)

개체 배열 매개변수--오류: '문자' 필드에 불완전한 유형이 있습니다. (Object array parameter--error: field ‘letters’ has incomplete type)

C++에서 메모리 삭제 (Deleting memory in c++)

C++ 프로그램을 실행할 수 없습니다. No se ejecuta el programa (C++ i can't run a program. No se ejecuta el programa)

컴파일 시 변수의 이름과 수명 (Name and lifetime of variables at compile time)

control-c 후 Visual Studio 콘솔 프로그램 충돌 (visual studio console program crashes after control-c)

멤버 변수에 std::enable_if 또는 유사한 메서드 사용 (Using std::enable_if or similar method on member variable)

ifstream input_file(filename); (I am receiving an error "no matching function to call" in the line ifstream input_file(filename);)

ESP8266에서 잠시 실행하면 JsonData 크기가 0이 됩니다. (JsonData size becomes zero after awhile of running in ESP8266)

합에 대한 속도 문제(제수의 합) (Speed problem for summation (sum of divisors))

벡터 벡터에서 하위 벡터의 첫 번째 값을 찾기 위해 begin() 및 end() 반복기의 범위를 지정하는 방법은 무엇입니까? (How to specify a range for begin() and end() iterators to find first value of sub vector in a vector of vectors?)







코멘트