CTF-base64加解密

base64

是一种编码方式。把3个8bit变成4个6bit。然后不足补0,符号是’=’. 然后还有一张表。

测试

ZmxhZ3tUSEVfRkxBR19PRl9USElTX1NUUklOR30=
输出:
flag{THE_FLAG_OF_THIS_STRING}

代码

解密

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

char str[1010];
char dict(int x,bool flag) {
    if(x == 0) {
        if(flag) return '=';
        else return 'A';
    }
    else if(x < 26) {
        return 'A' + x;
    }
    else if(x < 52) {
        return 'a' + x - 26;
    }
    else if(x < 62){
        return '0' + x - 52;
    }
    else if(x == 63) return '+';
    else return '/';
}

char refdict(char x) {
    if(x >= 'A' && x <= 'Z') {
        return x - 'A';
    }
    else if(x >= 'a' && x <= 'z') {
        return x - 'a' + 26;
    }
    else if(x >= '0' && x <= '9') {
        return x - '0' + 52;
    }
    else if(x == '+') return 63;
    else if(x == '/') return 64;
    else if(x == '=') return 0;
}

int main() {
    while(gets(str)) {
        string ans = "";

        int len = strlen(str);
        for (int i = 0;i + 3 < len;i += 4) {
            int num = 0;
            for (int j = 0;j < 4;j ++) {
                num = (num << 6) + refdict(str[i * 4 + j]);
            }
            string tmp = "";
            for (int j = 0;j < 3;j ++) {
                int val = num & 0x000000ff;
                num >>= 8;
                tmp = char(val) + tmp;
            }
            ans = ans + tmp;
        }
        cout << ans << endl;
    }
}





加密

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

char str[1010];
char dict(int x,bool flag) {
    if(x == 0) {
        if(flag) return '=';
        else return 'A';
    }
    else if(x < 26) {
        return 'A' + x;
    }
    else if(x < 52) {
        return 'a' + x - 26;
    }
    else if(x < 62){
        return '0' + x - 52;
    }
    else if(x == 63) return '+';
    else return '/';
}

int main() {
    freopen("in.txt","r",stdin);

    while(gets(str)) {
        cout << str << endl;
        string ans = "";
        int len = strlen(str);
        int newlen = ((len + 2) / 3 ) * 3;
        for (int i = len;i < newlen;i ++) {
            str[i] = 0;
        }
        str[newlen] = '\0';

        for (int i = 0;i + 2 < newlen;i += 3) {
            int num = (int)str[i + 2] + (((int)str[i + 1]) << 8) + (((int)str[i]) << 16);
            string tmp = "";
            for (int j = 3;j >= 0;j --) {
                int cur = num & 0x0000003f; //i * 24 + j * 6
                tmp = dict(cur,i * 24 + j * 6 >= len) + tmp;
                num >>= 6;
            }
            ans = ans + tmp;
        }
        cout << ans << endl;
    }
}






你可能感兴趣的:(CTF-base64加解密)