Overclock.net - An Overclocking Community - View Single Post - Python Base64 encoding with a non-standard alphabet

View Single Post
post #3 of (permalink) Old 03-20-2014, 10:41 AM - Thread Starter
New to Overclock.net
Terrere's Avatar
Join Date: Feb 2013
Location: Mississippi, USA
Posts: 1,116
Rep: 59 (Unique: 39)
Originally Posted by jvolkman View Post

Your idea of replacing the characters should work. Use string.maketrans to create a translation table, and then use str.translate to use it.
import string
import base64

STANDARD_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
CUSTOM_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'

def encode(input):
  return base64.b64encode(input).translate(ENCODE_TRANS)

def decode(input):
  return base64.b64decode(input.translate(DECODE_TRANS))

Wow, thanks for the reply. I figured out last night that I could create a for loop to do the translations. When I was doing the conversions, I was using documentation from a report on the malware to compare my conversions. The tail end of the command was correct, but the conversion of the 6 "#" symbols didn't convert well. Your version is actually cleaner and more efficient than my loop.
import base64
import string

custom = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/"
Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
s = ""
encode = "######pslist"
result = base64.b64encode(encode);
for ch in result:
    if (ch in custom):
        s = s+custom[string.find(Base64,str(ch))]
    elif (ch == '='):
            s += "="

The loop also handles all of the padding. I came up with the base loop, but on checking for algorithms I had forgotten the presence of "=" paddings in Base64 and had to steal the idea from someone else.

Thanks again for affirming my thought of substitution.

If you can keep your head about you, when all about you are losing theirs... It's quite possible that you haven't fully grasped the situation.
Terrere is offline