Make a Base64 decoder

Make a Base64 decoder

A certain Crackme came out with a string encoded with something called custom_base64 ... To get the Flag, you have to decode it to find the original string. What is custom_base64 ... To find the answer, we went to the Amazon hinterland ...

Overview

There is a dictionary in which 000000 to 111111 are replaced with characters in the Base64 mechanism. In normal Base64, a dictionary to which ʻABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + /` is applied is used in order. The contents of the custom_base64 function were replaced with the specified dictionary. [Article implementing Base64] In this article, the decoder is implemented in Python with reference to 1.

How Base64 works

Encode

Roughly check the Base64 encoding process. See other sites for details.

  1. Convert the character string (ASCII) you want to change to binary (binary)
  2. Divide the binary into 6 bits
  3. When splitting, the last is less than 6 bits, so add 0 so that it becomes 6 bits.
  4. Convert 6bit to characters using conversion table
  5. Add "=" so that the number of characters is a multiple of 4 in order to output in Base64 by 4 bits each.
  6. Completion of base64 string !!

Decode

Decoding is easy if you understand the encoding mechanism! Basically, just follow the reverse procedure!

  1. Delete the added "="
  1. Convert the characters to binary using the conversion table and connect them.
  1. Divide the binary into 8 bits, and delete the 0s added in Encoding 3.
  1. Convert binary bits to ASCII
01001000 → H
01101111 → o
01100111 → g
01100101 → e
01001000 → H
01101111 → o
01100111 → g
01100101 → e
  1. Decoding is complete!

Try to program

custom_base64_decoder.py


import sys
import argparse
BYTE_SIZE = 8

# 000000 ->A function that creates a dictionary-type list character by character up to 111111
def makeDict(base64Dict_seed):
    dictionary = {}

    for i in range(0, 64):
        dictionary[format(i, '06b')] = base64Dict_seed[i]

    return dictionary


#A function that lists the string s separated by n characters
def split(string, n):
    split_list = []

    for i in range(0, len(string), n):
        split_list.append(string[i:i+n])

    return split_list


#If the string does not have n characters, it will be n characters`c`Add
def fillBlank(s, n, c):
    mod = len(s) % n

    if mod == 0:
        return s
    else:
        margin = n - mod
        return s + c * margin


#Passing a dictionary value returns the dictionary key
def getValue(key, items):
    for v in items.items():
        # print(v[1])
        if v[1] == key:
            # print(v)
            return v[0]
    return ''


def main():
    # -You can enter a custom dictionary by adding k
    parser = argparse.ArgumentParser(
    description='custom Base64 Decoder')
    parser.add_argument('-k', '--key', help="Use custom Seed to encrypt in base64 ", \
        default="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
    parser.add_argument('text', help='base text')
    args = parser.parse_args()


    # 0.Make a dictionary
    base64Dict = makeDict(args.key)


    # 1. '='Remove
    text = args.text.replace("=", '')

    binStr = ""


    # 2.Use the conversion table to convert characters to binary and connect them.
    for i in text:
        binStr += getValue(i, base64Dict)

    # 3.Divide the binary into 8 bits, encode 3.Since the 0s added by are left over, delete them.
    splitCount = 8
    s = split(binStr, splitCount)

    if (len(s[-1]) != 8):
        s.pop(-1)


    # 4.Convert binary bits to ASCII
    result =""

    for c in s:
        print(c + " → " + chr(int(c, 2)))
        result += chr(int(c, 2))

    print(result)

if __name__ == "__main__":
    main()

How to use

$ python3 customBase64Decoder.py <Base64 text>
$ python3 customBase64Decoder.py -k <Custom dictionary> <Base64 text>
$ python3 customBase64Decoder.py SG9nZUhvZ2U=
$ python3 customBase64Decoder.py -k xEPOKnvADqeG0m1VkZ47CM653jrtbzLsTc2ypoYUSWJ9ludQig+awf8XF/RNHBhI 4vBUjCcQj8C=

HogeHoge

Summary

Base64 I fully understood. With this, you can make an original Base64 and make secret communication, you did it

Sample code can be found on GitHub

--Encoder - https://github.com/itiB/sandpit/blob/master/tools/customBase64Encoder.py --Decoder - https://github.com/itiB/sandpit/blob/master/tools/customBase64Decoder.py

References

What is base64? ?? I implemented it for understanding --qiita https://qiita.com/PlanetMeron/items/2905e2d0aa7fe46a36d4

Recommended Posts

Make a Base64 decoder
Make a squash game
Make a function decorator
Make a distance matrix
I'll make a password!
Make a Nyan button
Make a Tetris-style game!
Let's make a Discord Bot.
Make a Blueqat backend ~ Part 1
Make a Blueqat backend ~ Part 2
Make a LINE BOT (chat)
Make a bookmarklet in Python
Make a fortune with Python
Make Responder a daemon (service)
Let's make a rock-paper-scissors game
Make a fire with kdeplot
Make a math drill print
Let's make a remote rumba [Hardware]
How to make a Japanese-English translation
Make a Santa classifier from a Santa image
Let's make a remote rumba [Software]
Make a Tweet box for Pepper
Let's make a GUI with python.
Make a sound with Jupyter notebook
Let's make a spot sale service 2
How to make a slack bot
Let's make a breakout with wxPython
Let's make a spot sale service 1
How to make a crawler --Advanced
How to make a recursive function
Make C compilation a little easier
python / Make a dict from a list.
[Python] Make the function a lambda function
How to make a deadman's switch
Make Flask a Cloud Native application
Make a filter with a django template
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
How to make a crawler --Basic
Make a model iterator with PySide
Make a curtain generator in Blender
Let's make a spot sale service 3
Let's make a shiritori game with Python
Make a video player with PySimpleGUI + OpenCV
[Python] How to make a class iterable
Try to make a kernel of Jupyter
Make a relation diagram of Python module
Make a rare gacha simulator with Flask
Make Jupyter Notebook a service on CentOS
Make a Notebook Pipeline with Kedro + Papermill
Make Unity Accelerator a service on Linux
Make a partially zoomed figure with matplotlib
Make a drawing quiz with kivy + PyTorch
Let's make a voice slowly with Python
Make a cascade classifier with google colaboratory
Let's make a simple language with PLY 1
Do you make something like a rocket?
Make a logic circuit with a perceptron (multilayer perceptron)
Let's make a multilingual site using flask-babel
Make a GIF animation with folder monitoring
I tried to make a Web API