[Python] 纯文本查看 复制代码 import base64
import re
def is_base64(s):
# Step 1: 检查字符串是否符合Base64的字符集格式
base64_pattern = re.compile(r'^[A-Za-z0-9+/]+={0,2}$')
if not base64_pattern.match(s):
return False
try:
# Step 2: 尝试解码并验证
decoded_data = base64.b64decode(s, validate=True)
# Step 3: 可以根据需求进一步验证解码后的数据,这里暂时返回True表示是Base64编码
return True
except (base64.binascii.Error, ValueError):
# 如果解码失败,则返回False
return False
# 测试示例
test_strings = [
"U29tZSB0ZXh0IGVuY29kaW5nIGluIEJhc2U2NA==", # Base64编码的字符串 (对应 "Some text encoding in Base64")
"12345==", # 非Base64编码的字符串
"QmFzZTY0IGVuY29kaW5n", # Base64编码的字符串 (对应 "Base64 encoding")
"VGhpcyBpcyBhbiBpbnZhbGlkIHRleHQ=", # Base64编码的字符串 (对应 "This is an invalid text"
]
for s in test_strings:
result = is_base64(s)
print(f"'{s}' is base64 encoded: {result}")
|