簡體   English   中英

嘗試讀取文本文件,使用XOR加密,然后將其寫入新的文本文件

[英]Trying to read a text file, Encrypt it with XOR, then Write it to a new text file

我正在嘗試設計一個程序,該程序將打開任何文本文件,將其讀取為字符串,使用XOR加密該字符串,並將該字符串寫入新的文本文件。 下面的代碼有效,但是會生成多個“系統提示音”。

我的瘋狂猜測是我沒有正確處理空格? 我不確定。 有什么想法我做錯了嗎?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ifstream inFile;
    ofstream outFile;

    // Define variables
    string fileName,
        key = "seacrest out";

    // Input
    cout << "Please enter the name of the file you wish to encrypt: ";
    cin >> fileName;
    cout << endl;

    inFile.open(fileName, ios::in | ios::binary);
    string str((istreambuf_iterator<char>(inFile)), istreambuf_iterator<char>()); // Reads a text file into a single string.
    inFile.close();
    cout << "The file has been read into memory as follows:" << endl;   
    cout << str << endl;
    system("pause");

    // Encryption
    cout << "The file has been encrypted as follows:" << endl;
    for (unsigned x = 0; x < str.size(); x++)           // Steps through the characters of the string.
        str[x] ^= key[x % key.size()];                  // Cycles through a multi-character encryption key, and encrypts the character using an XOR bitwise encryption.
    cout << str << endl;                                // This code works, but I get system beeps. Something is still wrong.

    // Write Encrypted File
    cout << "Please enter the file name to save the encrypted file under: ";
    cin >> fileName;
    cout << endl;

    outFile.open(fileName, ios::out | ios::binary);
    outFile.write(str.c_str(), str.size());         // Writes the string to the binary file by first converting it to a C-String using the .c_str member function.

    system("pause");

return 0;
}

您聽到的那些嗶聲等於文件中的0x07字節。 您可以通過不在控制台中打印二進制文件的內容來擺脫此問題。

嘗試自己做的榮譽。 問題是您沒有正確處理某些字符,例如空格可能會嘗試打印出來

char d =(字符)(7);

的printf( “%C \\ n” 個,d);

這被稱為鈴鐺字符。 這是XOR加密的簡單實現,但我建議您編寫自己的版本

http://programmingconsole.blogspot.in/2013/10/xor-encryption-for-alphabets.html

當您使用某個隨機密鑰對字節進行異或運算時,您將獲得一些異常的字節序列。 這些字節序列恰好對應於一些不可打印的字符,您可以通過將其發送到控制台來使控制台發出蜂鳴聲。

如果刪除線

cout << str << endl;

您會發現您的控制台不再發出嗶聲,因為您沒有打印控制台解釋為嗶聲的錯誤字節序列。

如果您的控制台設置為ASCII模式(我假設是因為您有system("PAUSE") ,這表明您使用的是Windows操作系統,但除非您明確設置IIRC,否則該控制台不是Unicode),那么這些不可打印的字符都是字節小於0x1F和字節0x7F,並且導致控制台發出蜂鳴聲的字符為0x7(稱為“響鈴”)。

TL;博士

您在加密的數據中得到一些0x7字節,導致打印時控制台發出蜂鳴聲。 刪除cout << str << endl; 要解決這個問題。

暫無
暫無

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

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