Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is encoded in base64 using Python

Tags:

python

base64

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

like image 593
lizzie Avatar asked Sep 07 '12 09:09

lizzie


People also ask

How do I check if a string is base64 encoded in Python?

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. That's it!

How do I check if a string is encoded by base64?

In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.

What does == mean in base64?

The equals sign "=" represents a padding, usually seen at the end of a Base64 encoded sequence. Each group of six bits is encoded using the above conversion.

How do you decode a base64 encoded string in Python?

To decode an image using Python, we simply use the base64. b64decode(s) function. Python mentions the following regarding this function: Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.


1 Answers

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 
like image 125
id01 Avatar answered Sep 23 '22 11:09

id01