CTF-base64加解密

base64

是一種編碼方式。把3個8bit變成4個6bit。然後不足補0,符號是’=’. 然後還有一張表。

測試

ZmxhZ3tUSEVfRkxBR19PRl9USElTX1NUUklOR30=
輸出:
flag{THE_FLAG_OF_THIS_STRING}

代碼

解密

#include <iostream>
#include <cstring>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
#include <string>
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 <iostream>
#include <cstring>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <map>
#include <vector>
#include <string>
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;
    }
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章