Ever since I started playing CTFs I found myself decoding various base flags and whilst some of them were pretty straight forward, occasionally, you will find one that is encoded several times and even using various base encodings in the process.

How to decode these with Python easily? Well, all you need is this:

import base64
f = open("b64.txt", "r").read()
for i in range(0,50):
	f = base64.b64decode(f)
print(f)

The idea behind it is very simple:

  • you import the base64 module so you can leverage the b[xx]decode function
  • you read the flag file and store the contents in a variable
  • you iterate through the variable (in this case I needed to do so 50 times) using a for loop until the string is decoded
    • note that you will need to constantly update your initial variable as the for loop progresses in order to keep decoding the previous result, this is the reason why f will get a new value with each iteration. If you don’t update it, you will end up decoding the initial string 50 times instead.
  • you read the final value stored in the variable after the iterations are over

The same idea can be implemented when dealing with multiple base encodings. For example, I was working on a flag earlier that was encoded 5 times with base64, 5 times with base32 and 5 times with base16

While I am not sure this is the most efficient way to do it, the same principle applies and I was able to easily get the flag.

import base64
f = open("flag.txt", "r").read()
b16dec = ''
b32dec = ''
b64dec = ''
for i in range(0,5):
	f = base64.b16decode(f)
	b16dec = f
for i in range(0,5):
	b16dec = base64.b32decode(b16dec)
	b32dec = b16dec
for i in range(0,5):
	b32dec = base64.b64decode(b32dec)
	b64dec = b32dec
print(b64dec)

I hope this helps someone struggling as I’ve been struggling with it myself for a few hours when I started out.