简单加密无法正常工作

时间:2016-04-19 04:46:07

标签: c++

我正在使用我在网上找到的简单加密。基本上,我正在一个文件中流式传输,检查该文件是否打开(如果没有,显示错误消息)并在加密信息时将每行放在数组的每个元素中。然后,我将加密的信息传输到输出文件。

但是,我的output.txt文件中没有任何内容。如果你自己测试它,加密就可以了。

这是我的代码:

#include <string>  
#include <fstream>
#include <sstream> // for ostringstream
#include <iostream>
#include <stdio.h>
#include <algorithm>

/* Credits to kylewbanks.com */
string encrypt (string content) {
    char key[3] = {'K'}; //Any chars will work
    string output = content;

    for (int i = 0; i < content.size(); i++)
        output[i] = content[i] ^ key[i % (sizeof(key) / sizeof(char))];

    return output;
}

int main() {
    string input, line;
    string content[10000];
    string encryptedContent[10000];

        int counter = 0, innerChoice = 0, i, finalCounter;

        cout << "\tPlease enter the file name to encrypt!\n";
        cout << "\tType '0' to get back to the menu!\n";
        cout << "Input >> ";

        cin >> input;

        /* Reads in the inputted file */
        ifstream file(input.c_str());
        //fopen, fscanf

        if(file.is_open()) {

            /* Counts number of lines in file */
            while (getline(file, line)) {
                counter++;
            }

            cout << counter;

            finalCounter = counter;

            for (i = 0; i < finalCounter; i++) {
                file >> content[i];
                encryptedContent[i] = encrypt(content[i]);
                cout << encryptedContent[i];
            }
        } else {
            cout << "\tUnable to open the file: " << input << "!\n";
        }

        /* Write encryption to file */
        ofstream outputFile("output.txt");
        for (i = 0; i < finalCounter ; i++) {
            outputFile << encryptedContent;
        }
        outputFile.close();
}

有任何疑问是什么问题?

1 个答案:

答案 0 :(得分:1)

string content[10000];
string encryptedContent[10000];

这是错误的,因为它创建了20000个字符串(您可能认为它正在创建足够大的字符数组来读取数据)。

string content;就足够了。它可以调整大小以处理任何长度的字符串。

您只需要以二进制读取/写入文件:

int main() 
{
    string input = "input.txt";
    ifstream file(input, ios::binary);
    if (!file.is_open())
    {
        cout << "\tUnable to open the file: " << input << "!\n";
        return 0;
    }

    string plaintext;

    //read the file    
    file.seekg(0, std::ios::end);
    size_t size = (size_t)file.tellg();
    file.seekg(0);
    plaintext.resize(size, 0);
    file.read(&plaintext[0], size);

    cout << "reading:\n" << plaintext << "\n";

    //encrypt the content
    string encrypted = encrypt(plaintext);

    //encrypt again so it goes back to original (for testing)
    string decrypted = encrypt(encrypted);

    cout << "testing:\n" << decrypted << "\n";

    /* Write encryption to file */
    ofstream outputFile("output.txt", ios::binary);
    outputFile.write(encrypted.data(), encrypted.size());

    return 0;
}