Check If A String Is Encoded In Base64 Using Python


Answer :

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 

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

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.


Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Change The Font Size Of Visual Studio Solution Explorer