Check if a string is encoded in base64 using Python

前端 未结 10 2034
离开以前
离开以前 2021-02-05 01:56

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

相关标签:
10条回答
  • 2021-02-05 02:27

    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()
    
    0 讨论(0)
  • 2021-02-05 02:30

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

    0 讨论(0)
  • 2021-02-05 02:31
    import base64
    import binascii
    
    try:
        base64.decodestring("foo")
    except binascii.Error:
        print "no correct base64"
    
    0 讨论(0)
  • 2021-02-05 02:37

    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
    
    0 讨论(0)
提交回复
热议问题