Check if a string is encoded in base64 using Pytho

2020-05-25 06:55发布

Is there a good way to check if a string is encoded in base64 using Python?

标签: python base64
9条回答
一夜七次
2楼-- · 2020-05-25 07:35

if the length of the encoded string is the times of 4, it can be decoded

base64.encodestring("whatever you say").strip().__len__() % 4 == 0

so, you just need to check if the string can match something like above, then it won't throw any exception(I Guess =.=)

if len(the_base64string.strip()) % 4 == 0:
    # then you can just decode it anyway
    base64.decodestring(the_base64string)
查看更多
We Are One
3楼-- · 2020-05-25 07:38
def is_base64(s):
    s = ''.join([s.strip() for s in s.split("\n")])
    try:
        enc = base64.b64encode(base64.b64decode(s)).strip()
        return enc == s
    except TypeError:
        return False

In my case, my input, s, had newlines which I had to strip before the comparison.

查看更多
Emotional °昔
4楼-- · 2020-05-25 07:39
x = 'possibly base64 encoded string'
result = x
try:
   decoded = x.decode('base64', 'strict')
   if x == decoded.encode('base64').strip():
       result = decoded
except:
   pass

this code put in the result variable decoded string if x is really encoded, and just x if not. Just try to decode doesn't always work.

查看更多
登录 后发表回答