我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。
我如何检查一个字符串是否被Base64编码?
我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。
我如何检查一个字符串是否被Base64编码?
当前回答
不可能检查一个字符串是否是base64编码的。只有当该字符串是base64编码的字符串格式时才有可能验证,这意味着它可能是由base64编码生成的字符串(为了验证这一点,可以根据regexp验证字符串,也可以使用库,这个问题的许多其他答案提供了很好的检查方法,所以我不会详细讨论)。
例如,string flow是一个有效的base64编码的字符串。但不可能知道它只是一个简单的字符串,一个英语单词流,还是它是以64为基数编码的字符串~Z0
其他回答
/^([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==)$/
这个正则表达式帮助我在rails中识别我的应用程序中的base64,我只有一个问题,它识别字符串“errorDescripcion”,我生成一个错误,解决它只是验证字符串的长度。
这在Python中是有效的:
import base64
def IsBase64(str):
try:
base64.b64decode(str)
return True
except Exception as e:
return False
if IsBase64("ABC"):
print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
else:
print("ABC is NOT Base64-encoded.")
if IsBase64("QUJD"):
print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
else:
print("QUJD is NOT Base64-encoded.")
IsBase64("string here")如果这里的字符串是base64编码的则返回true,如果这里的字符串不是base64编码的则返回false。
没有办法区分字符串和base64编码,除非字符串在您的系统中有一些特定的限制或标识。
Base64有许多变体,所以考虑只确定您的字符串是否类似于您期望处理的变体。因此,您可能需要根据索引和填充字符(即+,/,=)调整下面的正则表达式。
class String
def resembles_base64?
self.length % 4 == 0 && self =~ /^[A-Za-z0-9+\/=]+\Z/
end
end
用法:
raise 'the string does not resemble Base64' unless my_string.resembles_base64?
对于Java风格,我实际上使用以下正则表达式:
"([A-Za-z0-9+]{4})*([A-Za-z0-9+]{3}=|[A-Za-z0-9+]{2}(==){0,2})?"
在某些情况下,==也是可选的。
最好!