#include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<fstream>
using namespace ::std;
string code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
bool isEq(string str);
string getString(string name);
void encode(string str);
void reverse(bitset<8>& tmp);
void decode(string str);
int main()
{
string str = "", res = "";
int ch;
cout << "请输入选项(1编码,2解码,3隐写,4破解隐写):" << endl;
cin >> ch;
while (ch)
{
switch (ch)
{
case 1:str = getString("ToBeEncode.txt"); encode(str); break;
case 2:str = getString("CodeFile.txt"); decode(str); break;
case 3:break;
case 4:break;
}
cout << "请输入选项:" << endl;
cin >> ch;
}
return 0;
}
string getString(string name)
{
fstream file;
string res = "";
char c;
file.open(name, ios::in);
while ((c = file.get()) != EOF)
{
res.push_back(c);
}
return res;
}
void encode(string str)
{
fstream file2;
file2.open("CodeFile.txt", ios::out);//写入编码结果
string res = "";
uint8_t c = 0x00;
int cnt = 0;
while (str.size() % 3 != 0)
{
str.push_back(0x00);
}
for (int i = 0; i < str.size(); i++)
{
bitset<8> tmp = str[i];
reverse(tmp);
for (int j = 0; j < 8; j++)
{
if (cnt == 6)
{
c >>= 1;
res.push_back(code[c]);
cnt = 0;
c = 0x00;
}
c |= tmp[j];
c <<= 1;
cnt++;
}
}
while (8 * str.size() > 6 * res.size())
{
res.push_back('=');
}
file2 << res;
}
void reverse(bitset<8>& tmp)
{
int a = 0, b = 7;
while (a < b)
{
long long t = tmp[a];
tmp[a] = tmp[b];
tmp[b] = t;
a++;
b--;
}
}
void decode(string str)
{
fstream file;
file.open("ToBeEncode.txt", ios::out);
string res = "";
while (isEq(str))
{
str.pop_back();
}
vector<uint8_t> p;
for (int i = 0; i < str.size(); i++)
{
for (int j = 0; j < code.size(); j++)
{
if (code[j] == str[i])
{
p.push_back(j);
}
}
}
for (int i = 0; i < p.size() - 1; i++)
{
uint8_t tmp;
if (i % 4 == 0)
{
tmp = (p[i] << 2) | (p[i + 1] >> 4);
res.push_back(tmp);
}
else if(i % 4 == 1)
{
tmp = (p[i] << 4) | (p[i + 1] >> 2);
res.push_back(tmp);
}
else if (i % 4 == 2)
{
tmp = (p[i] << 6) | p[i + 1];
res.push_back(tmp);
}
}
file << res;
}
bool isEq(string str)
{
bool res = false;
for (int i = str.size() - 1; i >= 0; i--)
{
if (str[i] == '=')
{
res = true;
break;
}
}
return res;
}
|