Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - decode base64 like string with different index table(s)

My problem is, that I have something encoded (base64 like) with a differnet index table:

0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/

instead of

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

so when I use base64.b64decode() it gives me a wrong result. Is there a way to set this table durring conversion (as a parameter maybe)?

Or should I "convert" the wrong base64 string, I mean replace 0 to A, 1 to B, etc... and than use base64decode? if so what is the best and fast workaround for this?

update1: I use this, which works, but looks a bit slow, and unprofessional. :)

def correctbase64(str):
  dicta = [ ['0','A'], ['1','B'], ['2','C'], ['3','D'], ['4','E'], ['5','F'], ['6','G'], ['7','H'], ['8','I'], ['9','J'], ['A','K'], ['B','L'], ['C','M'], ['D','N'], ['E','O'], ['F','P'], ['G','Q'], ['H','R'], ['I','S'], ['J','T'], ['K','U'], ['L','V'], ['M','W'], ['N','X'], ['O','Y'], ['P','Z'], ['Q','a'], ['R','b'], ['S','c'], ['T','d'], ['U','e'], ['V','f'], ['W','g'], ['X','h'], ['Y','i'], ['Z','j'], ['a','k'], ['b','l'], ['c','m'], ['d','n'], ['e','o'], ['f','p'], ['g','q'], ['h','r'], ['i','s'], ['j','t'], ['k','u'], ['l','v'], ['m','w'], ['n','x'], ['o','y'], ['p','z'], ['q','0'], ['r','1'], ['s','2'], ['t','3'], ['u','4'], ['v','5'], ['w','6'], ['x','7'], ['y','8'], ['z','9'] ]
  l = list(str)
  for i in range(len(l)):
    for c in dicta:
      if l[i] == c[0]:
        l[i] = c[1]
        break
  return "".join(l)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this should work (WARNING: untested code; may be full of mistakes):

import string

my_base64chars  = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"
std_base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

s = s.translate(string.maketrans(my_base64chars, std_base64chars))
data = base64.b64decode(s)

It isn't possible to make the standard base64 functions (or the lower-level ones in binascii that they call) use a custom table.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...