我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。

我如何检查一个字符串是否被Base64编码?


当前回答

在Java中,以下代码适用于我:

public static boolean isBase64Encoded(String s) {
        String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(s);
        return m.find();
    }

其他回答

PHP5试试这样做

//where $json is some data that can be base64 encoded
$json=some_data;

//this will check whether data is base64 encoded or not
if (base64_decode($json, true) == true)
{          
   echo "base64 encoded";          
}
else 
{
   echo "not base64 encoded"; 
}

在PHP7中使用这个

 //$string parameter can be base64 encoded or not

function is_base64_encoded($string){
 //this will check if $string is base64 encoded and return true, if it is.
 if (base64_decode($string, true) !== false){          
   return true;        
 }else{
   return 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})?"

在某些情况下,==也是可选的。

最好!

检查字符串的长度是否为4的倍数。然后使用这个正则表达式来确保字符串中的所有字符都是base64字符。

\A[a-zA-Z\d\/+]+={,2}\z

如果您使用的库添加换行符作为遵守每行最多76个字符规则的一种方式,请将它们替换为空字符串。