Check if a string is encoded in base64 using Python

前端 未结 10 2044
离开以前
离开以前 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: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.

提交回复
热议问题