How to determine if a string is Base64Encoded or not?

What is the best way to determine if a Base64Encoded string is or not (using Delphi)?

+6
source share
4 answers

The best thing is to try to decode it. If decoding failed, the input was not base64 encoded. It successfully decodes the string, then the input could be base64 encoded.

+5
source

You can check if a string contains only Base64 valids characters

function StringIsBase64(const InputString : String ) : Boolean; const Base64Chars: Set of AnsiChar = ['A'..'Z','a'..'z','0'..'9','+','/','=']; var i : integer; begin Result:=True; for i:=1 to Length(InputString) do {$IFDEF UNICODE} if not CharInSet(InputString[i],Base64Chars) then {$ELSE} if not (InputString[i] in Base64Chars) then {$ENDIF} begin Result:=False; break; end; end; 

= Char is used for padding, so you can add extra validation to the function for base64 padded strings to check if the string length is mod 4

+5
source

In addition to the RRUZ answer, you can also check the length of the string (it is a multiple of 4).

 function IsValidBase64(const aValue: string): Boolean; var i: Integer; lValidChars: set of Char; begin Result := aValue <> ''; lValidChars := ['a'..'z', 'A'..'Z', '0'..'9', '/', '+']; //length of string should be multiple of 4 if Length(aValue) mod 4 > 0 then Result := False else for i := 1 to Length(aValue) do begin if aValue[i] = '=' then begin if i < Length(aValue) - 1 then begin Result := False; Exit; end else lValidChars := ['=']; end else if not (aValue[i] in lValidChars) then begin Result := False; Break; end; end; end; 

Please note that this code is Delphi 7 code and is not configured to use Unicode.

+4
source

As already mentioned here, there is no reliable check if a certain string is encoded by Base64 or not, so even if you consider the input as a valid Base64 string encoding, this does not mean that the string is actually encoded in this way, I am only posting another version of the verification function here which according to RFC 4648 confirms:

  • if the input string is not empty and its length is a multiple of 4
  • if the input line contains no more than two complementary characters and only at the end of the line
  • if the input line contains only characters from the Base64 alphabet (see Page 5, Table 1 )

 function IsValidBase64EncodedString(const AValue: string): Boolean; const Base64Alphabet = ['A'..'Z', 'a'..'z', '0'..'9', '+', '/']; var I: Integer; ValLen: Integer; begin ValLen := Length(AValue); Result := (ValLen > 0) and (ValLen mod 4 = 0); if Result then begin while (AValue[ValLen] = '=') and (ValLen > Length(AValue) - 2) do Dec(ValLen); for I := ValLen downto 1 do if not (AValue[I] in Base64Alphabet) then begin Result := False; Break; end; end; end; 
+3
source

Source: https://habr.com/ru/post/894010/


All Articles