紀錄

使用 XOR 進行簡易加密,目前進行 2 次 XOR 運算 ( 太多次中文字會出錯 )

作法

  • 加密:隨機產生兩個數字,並將內容對這兩個數字做 XOR,最後這兩個數字對 9 做一次 XOR 並儲存在第一行
  • 解密:先讀取第一行並對 9 做一次 XOR 可以得到兩個加密的數字,再將內容對這兩個數字做 XOR 並儲存即可

用法

將要加密或解密的文字放在 data.txt 裡

  • 加密:執行完成後會產生 encrypted.txt,裡面即是加密後的內容
  • 解密:執行完成後會產生 decrypted.txt,裡面即是加密後的內容

已知 Bug

  • 中文字有時會出錯 ( 變成其他文字或符號 )
  • 符號有時會出錯 ( 會不見 )

努力方向

  • 解決掉上面的 Bug
  • 讓程式更有效率 ( 目前太多迴圈 )

code

2020-07-08 第一版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <fstream>
#include <ctime>
#include <vector>
#include <string>

using namespace std;

#define encryptTimes 2

void readFile(vector< string >& data); // 讀取 data.txt
void produceCode(vector< int >& code); // 產生加密的數字
void saveCode(vector< string >& data, vector< int >& code); // 轉換
void convert(vector< string >& data, vector< int >& code); // 將加密的數字轉換並存在第一行

int main()
{
int choice;
string temp;
vector< int > code;
vector< string > data;

cout << "Welcome! Input 1 to encrypt, 2 to decrypt: ";
cin >> choice;

if (choice == 1)
{
readFile(data); // 讀取 data.txt
produceCode(code); // 產生加密的數字
convert(data, code); // 轉換
saveCode(data, code); // 將加密的數字轉換並存在第一行

ofstream outFile("encrypted.txt"); // 輸出
for (auto& i : data)
outFile << i << endl;
cout << endl << "encrypt completed." << endl;
}
else if (choice == 2)
{
readFile(data); // 讀取 data.txt

string readcode = data[0]; // 第一行為加密的數字
data.erase(data.begin()); // 刪除掉第一行
for (auto& i : readcode) // 將第一行轉換
code.push_back((i ^ 9) - 'a');

convert(data, code); // 轉換
ofstream outFile("decrypted.txt"); // 輸出
for (auto& i : data)
outFile << i << endl;
cout << endl << "decrypt completed." << endl;
}
}

void readFile(vector< string >& data)
{
string temp;
ifstream inFile("data.txt");
if (!inFile)
{
cout << endl << "There is no file." << endl;
exit(0);
}
while (getline(inFile, temp))
data.push_back(temp);
}

void produceCode(vector< int >& code)
{
srand((unsigned)time(NULL));
int codetemp;
while (code.size() < encryptTimes)
{
codetemp = rand() % 10;
auto it = find(code.begin(), code.end(), codetemp);
if (it == code.end())
code.push_back(codetemp);
}
}

void saveCode(vector< string >& data, vector< int >& code)
{
string savecode;
for (auto& i : code)
savecode.push_back(('a' + i) ^ 9);
data.insert(data.begin(), savecode);
}

void convert(vector< string >& data, vector< int >& code)
{
for (auto& i : data)
for (auto& j : i)
for (auto& k : code)
if (j != 32)
j ^= k;
}