CodeSignal - Weird Encoding

CodeSignal - Weird Encoding

Python - Picturing the Parsibilities

·

3 min read

You've been actively exchanging emails with one of your colleagues and noticed that you can't open his attachments. Unfortunately, he's just gone on vacation and you need these attached files right now.

You've spent some time studying his emails and discovered that your colleague used the buggy email client which instead of using proper MIME Base64 encoding for the attachments used other variants differing in characters that represent values 62 and 63.
Furthermore, different versions of this email client used different variations of the encoding!

Given the encoding of the email client which was used to send attachment,
decode it.

Here is the default Base64 encoding table:

ValueCharValueCharValueCharValueChar
0A16Q32g48w
1B17R33h49x
2C18S34i50y
3D19T35j51z
4E20U36k520
5F21V37l531
6G22W38m542
7H23X39n553
8I24Y40o564
9J25Z41p575
10K26a42q586
11L27b43r597
12M28c44s608
13N29d45t619
14O30e46u62+
15P31f47v63/

Example

For encoding = "-_" and message = "Q29kZVNpZ25hbA==", the output should be
solution(encoding, message) = "CodeSignal".

Use the base64 package.

def solution(encoding, message):
    import base64
    import string

    base64chars = string.ascii_uppercase + string.ascii_lowercase + string.digits + string.digits + "+/"
    mybase64chars = base64chars[:-2] + encoding

    m = message.translate(str.maketrans(mybase64chars, base64chars))
    return base64.b64decode(m).decode('utf-8')

Turns out that there is even a parameter for alternate characters or altchars:

def solution(encoding, message):
    from base64 import b64decode
    return b64decode(message, encoding).decode("utf-8")

References