Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.7 kB
2
Indexable
Never
#include <iostream>
#include <string>
using namespace std;
namespace base64 {
    std::string decode(const std::string& input);
    std::string encode(const std::string& input);
}
 
const std::string chars = // base64 table
   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 
int find_idx(const char c) {
    if (c >= 'A' && c <= 'Z') {
        return c - 'A';
    } else if (c >= 'a' && c <= 'z') {
        return c - 'a' + 26;
    } else if (c >= '0' && c <= '9') {
        return c - '0' + 52;
    } else if (c == '+') {
        return 62;
    } else if (c == '/') {
        return 63;
    }
}
std::string base64::decode(const std::string& input)
{
	string result = "";
	int n=input.size();
	for(int i=0;i<n/4-1;i++){
		char asc_1 = find_idx(input[4*i]) << 2 | find_idx(input[4*i+1]) >> 4;
		char asc_2 = (find_idx(input[4*i+1]) & 0x0F) << 4 | find_idx(input[4*i+2]) >> 2;
		char asc_3 = (find_idx(input[4*i+2]) & 0x03) << 6 | find_idx(input[4*i+3]);
		result.push_back(asc_1);
		result.push_back(asc_2);
		result.push_back(asc_3);
	}
	char asc_1 = find_idx(input[n-4]) << 2 | find_idx(input[n-3]) >> 4;
	result.push_back(asc_1);
	if(input[n-2]=='='){
	}
	else{
		
		char asc_2 = (find_idx(input[n-3]) & 0x0F) << 4 |find_idx(input[n-2])>>2;
		result.push_back(asc_2);
		
		if(input[n-1]=='='){
			
		}
		else{
			char asc_3 = (find_idx(input[n-2]) & 0x03) << 6| find_idx(input[n-1]) ;
			result.push_back(asc_3);
		}
	}
	return result; 
}

std::string base64::encode(const std::string& input)
{
	string result = "";
	int n=input.size();
	for(int i=0;i<n/3;i++){
		char b64_1 = chars[input[3*i]>>2];
		char b64_2 = chars[(input[3*i] & 0b00000011) << 4 | (input[3*i+1] & 0b11110000) >> 4];
		char b64_3 = chars[(input[3*i+1] & 0b00001111) << 2 | (input[3*i+2] & 0b11000000) >> 6];
		char b64_4 = chars[input[3*i+2] & 0b00111111];
		
		result.push_back(b64_1);
		result.push_back(b64_2);
		result.push_back(b64_3);
		result.push_back(b64_4);
	} 
	if(n%3==1){
		char b64_1 = chars[input[n-1]>>2];
		char b64_2 = chars[(input[n-1] & 0b00000011) << 4 ];
		char b64_3 = '=';
		char b64_4 = '=';
		result.push_back(b64_1);
		result.push_back(b64_2);
		result.push_back(b64_3);
		result.push_back(b64_4);
	}
	if(n%3==2){
		char b64_1 = chars[input[n-2]>>2];
		char b64_2 = chars[(input[n-2] & 0b00000011) << 4 | (input[n-1] & 0b11110000) >> 4];
		char b64_3 = chars[(input[n-1] & 0b00001111) << 2 ];
		char b64_4 = '=';
		result.push_back(b64_1);
		result.push_back(b64_2);
		result.push_back(b64_3);
		result.push_back(b64_4);
	}
	return result;
}