base64编码与解码

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值