簡體   English   中英

簡單加密不起作用

[英]Simple Encryption not working

我正在使用我在網上找到的簡單加密。 基本上,我正在流式傳輸文件,檢查該文件是否打開(如果沒有,則顯示錯誤消息)並在加密信息的同時將每一行放入數組的每個元素中。 之后,我將該加密信息流式傳輸到輸出文件中。

但是,我的 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();
}

任何線索出了什么問題?

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM