2010-07-28 16 views
16

Ho cercato come convalidare una stringa base64 e mi sono imbattuto in questo.La convalida della stringa è in formato base64 utilizzando RegEx?

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

Ho bisogno di un piccolo aiuto per consentire "==" e "=".

Grazie

+0

Cosa intendi? '==' e '=' sono già consentiti. – kennytm

+0

Sì, hai ragione, funziona. Scusate se stavo solo aggiungendo un extra "=" sulla mia stringa codificata per testare quando avevo bisogno di creare una nuova stringa codificata che contenga "==" :) – arbme

+0

nota che il segno più deve essere sfuggito. così: '^ (?: [A-Za-z0-9 \ + /] {4}) * (?: [A-Za-z0-9 \ + /] {2} == | [A-Za -z0-9 \ + /] {3} =)? $ ' –

risposta

21

Questo dovrebbe svolgere molto bene.

private static readonly HashSet<char> _base64Characters = new HashSet<char>() { 
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 
    'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 
    '=' 
}; 

public static bool IsBase64String(string value) 
{ 
    if (string.IsNullOrEmpty(value)) 
    { 
     return false; 
    } 
    else if (value.Any(c => !_base64Characters.Contains(c))) 
    { 
     return false; 
    } 

    try 
    { 
     Convert.FromBase64String(value); 
     return true; 
    } 
    catch (FormatException) 
    { 
     return false; 
    } 
} 
+0

+1 Per la soluzione più semplice. –

+0

Preferirei la chiarezza di questa versione a meno che non si aspettino molti dati non validi. – Justin

+0

Potrebbe anche usare Base64 per controllare piuttosto che RegEx ... ha senso;) – arbme

8

Ho aggiornato il codice di cui sopra un po 'di incontrare alcuni più requisiti:

  • di controllo per la corretta dimensione della stringa (dovrebbe essere multiplo di 4)
  • controllo per il conteggio dei caratteri pad (dovrei essere fino a 2 carattere alla fine della stringa solo)
  • farlo funzionare in .NET 2.0 (o meglio, dovrebbe essere attuato il HashSet<T> oppure utilizzare Dictionary<T, U>)

Il codice è una parte della mia biblioteca asserzione, quindi questo è il motivo per cui ci sono due metodi di controllo e il parametro param ...

private const char Base64Padding = '='; 

    private static readonly HashSet<char> Base64Characters = new HashSet<char>() 
    { 
     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
     'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 
     'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 
     'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' 
    }; 

    public static void CheckBase64String(string param, string paramName) 
    { 
     if (CheckBase64StringSafe(param) == false) 
     { 
      throw (new ArgumentException(String.Format("Parameter '{0}' is not a valid Base64 string.", paramName))); 
     } 
    } 

    public static bool CheckBase64StringSafe(string param) 
    { 
     if (param == null) 
     { 
      // null string is not Base64 something 
      return false; 
     } 

     // replace optional CR and LF characters 
     param = param.Replace("\r", String.Empty).Replace("\n", String.Empty); 

     if (param.Length == 0 || 
      (param.Length % 4) != 0) 
     { 
      // Base64 string should not be empty 
      // Base64 string length should be multiple of 4 
      return false; 
     } 

     // replace pad chacters 
     int lengthNoPadding = param.Length; 
     int lengthPadding; 

     param = param.TrimEnd(Base64Padding); 
     lengthPadding = param.Length; 

     if ((lengthNoPadding - lengthPadding) > 2) 
     { 
      // there should be no more than 2 pad characters 
      return false; 
     } 

     foreach (char c in param) 
     { 
      if (Base64Characters.Contains(c) == false) 
      { 
       // string contains non-Base64 character 
       return false; 
      } 
     } 

     // nothing invalid found 
     return true; 
    } 

io non ho provato il codice estensivamente, in modo non ci sono garanzie di funzionalità!

Problemi correlati