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

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


当前回答

当你知道原始内容的长度(例如校验和)时,这个片段可能会很有用。它检查编码的表单是否具有正确的长度。

public static boolean isValidBase64( final int initialLength, final String string ) {
  final int padding ;
  final String regexEnd ;
  switch( ( initialLength ) % 3 ) {
    case 1 :
      padding = 2 ;
      regexEnd = "==" ;
      break ;
    case 2 :
      padding = 1 ;
      regexEnd = "=" ;
      break ;
    default :
      padding = 0 ;
      regexEnd = "" ;
  }
  final int encodedLength = ( ( ( initialLength / 3 ) + ( padding > 0 ? 1 : 0 ) ) * 4 ) ;
  final String regex = "[a-zA-Z0-9/\\+]{" + ( encodedLength - padding ) + "}" + regexEnd ;
  return Pattern.compile( regex ).matcher( string ).matches() ;
}

其他回答

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编码的字符串格式时才有可能验证,这意味着它可能是由base64编码生成的字符串(为了验证这一点,可以根据regexp验证字符串,也可以使用库,这个问题的许多其他答案提供了很好的检查方法,所以我不会详细讨论)。

例如,string flow是一个有效的base64编码的字符串。但不可能知道它只是一个简单的字符串,一个英语单词流,还是它是以64为基数编码的字符串~Z0

对于Flutter,我测试了上面的几个注释,并将其转换为dart函数,如下所示

  static bool isBase64(dynamic value) {

    if (value.runtimeType == String){
      
      final RegExp rx = RegExp(r'^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$',
          multiLine: true,
          unicode: true,
      );

      final bool isBase64Valid = rx.hasMatch(value);

      if (isBase64Valid == true) {return true;}
      else {return false;}

    }

    else {return false;}

  }

您可以使用以下正则表达式来检查字符串是否构成有效的base64编码:

^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$

在base64编码中,字符集为[A-Z, A-Z, 0-9和+ /]。如果其余长度小于4,则字符串用'='字符填充。

^([A-Za-z0-9+/]{4})*表示字符串以0个或多个base64组开头。

([A-Za-z0-9 + /] {4} | [A-Za-z0-9 + /] {3} = | [A-Za-z0-9 + /]{2} = =)意味着美元的字符串以三种形式之一:A-Za-z0-9 + / {4}, {3} = [A-Za-z0-9 + /]或[A-Za-z0-9 + /]{2} = =。

这在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。