57

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

11 Answers 11

81

I was looking for a solution to the same problem, then a very simple one just struck me in the head. All you need to do is decode, then re-encode. If the re-encoded string is equal to the encoded string, then it is base64 encoded.
Here is the code:

import base64

def isBase64(s):
    try:
        return base64.b64encode(base64.b64decode(s)) == s
    except Exception:
        return False

That's it!

Edit: Here's a version of the function that works with both the string and bytes objects in Python 3:

import base64

def isBase64(sb):
        try:
                if isinstance(sb, str):
                        # If there's any unicode here, an exception will be thrown and the function will return false
                        sb_bytes = bytes(sb, 'ascii')
                elif isinstance(sb, bytes):
                        sb_bytes = sb
                else:
                        raise ValueError("Argument must be string or bytes")
                return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes
        except Exception:
                return False
Sign up to request clarification or add additional context in comments.

10 Comments

Nice and simple, I like it!
Side note: you can always just return base64.b64encode(base64.b64decode(s)) == s instead of using an if statement and returning a constant bool result :)
isBase64('test') return True
@ahmed that's because "test" is a valid base64 string. Base64 includes a-z, A-Z, 0-9, +, /, and = for padding.
on Python3 since str and bytes comparison doesn't covert them to same type implicitly(for the comparison) I had to do return base64.b64encode(base64.b64decode(s)).decode() == s for this to work. As my s was a unicode str while the value returned from base64.b64encode(base64.b64decode(s)) was bytes. See this: stackoverflow.com/q/30580386/1781024
|
37
import base64
import binascii

try:
    base64.decodestring("foo")
except binascii.Error:
    print "no correct base64"

9 Comments

I don't find any in the documentation.
"easier to ask for forgiveness than permission", although I'd probably favour catching the actual exception that's likely to be raised (which I think will be binascii.Error)
This is incorrect, base64.decodestring('čččč') returns an empty string and no exception but I dont't think the string čččč is valid base64
base64.decodestring("dfdsfsdf ds fk") doesn't raise TypeError neither, the string doesn't seem to be a base64 string
base64.b64decode(s, validate=true) will decode s if it is valid, and otherwise throw an exception. base64.decodestring is very permissive and will strip any non-base64 characters which is potentially problematic.
|
28

This isn't possible. The best you could do would be to verify that a string might be valid Base 64, although many strings consisting of only ASCII text can be decoded as if they were Base 64.

2 Comments

Is this really the answer?
@coler-j yes, it is technically correct. It also probably should have been a comment but in 2012 SO was different. Maybe.
11

The solution I used is based on one of the prior answers, but uses more up to date calls.

In my code, the my_image_string is either the image data itself in raw form or it's a base64 string. If the decode fails, then I assume it's raw data.

Note the validate=True keyword argument to b64decode. This is required in order for the assert to be generated by the decoder. Without it there will be no complaints about an illegal string.

import base64, binascii

try:
    image_data = base64.b64decode(my_image_string, validate=True)
except binascii.Error:
    image_data = my_image_string

Comments

6

Using Python RegEx

import re

txt = "VGhpcyBpcyBlbmNvZGVkIHRleHQ="
x = re.search("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$", txt)

if (x):
  print("Encoded")
else:
  print("Non encoded")

Comments

3

Before trying to decode, I like to do a formatting check first as its the lightest weight check and does not return false positives thus following fail-fast coding principles.

Here is a utility function for this task:

RE_BASE64 = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"
def likeBase64(s:str) -> bool:
    return False if s is None or not re.search(RE_BASE64, s) else True

Comments

2

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)

1 Comment

This does not work for strings with \n in them that are still valid base64
2

@geoffspear is correct in that this is not 100% possible but you can get pretty close by checking the string header to see if it matches that of a base64 encoded string (re: How to check whether a string is base64 encoded or not).

# check if a string is base64 encoded.
def isBase64Encoded(s):
    pattern = re.compile("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$")
    if not s or len(s) < 1:
        return False
    else:
        return pattern.match(s)

Also not that in my case I wanted to return false if the string is empty to avoid decoding as there's no use in decoding nothing.

Comments

2

I know I'm almost 8 years late but you can use a regex expression thus you can verify if a given input is BASE64.

import re

encoding_type = 'Encoding type: '
base64_encoding = 'Base64'


def is_base64():
    element = input("Enter encoded element: ")
    expression = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"

    matches = re.match(expression, element)

    if matches:
        print(f"{encoding_type + base64_encoding}")
    else:
        print("Unknown encoding type.")


is_base64()

Comments

1
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.

Comments

0
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.

1 Comment

instead of x == decoded.encode('base64').strip() should be x == decoded.encode('base64').replace('\n', '') because of in some cases encode add several '\n'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.