Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a string is Base64Encoded or not?

Which is the best method to detect if a string is Base64Encoded or not (using Delphi)?

like image 867
MX4399 Avatar asked Aug 01 '11 06:08

MX4399


People also ask

How do I get base64 encoded strings?

If we were to Base64 encode a string we would follow these steps: Take the ASCII value of each character in the string. Calculate the 8-bit binary equivalent of the ASCII values. Convert the 8-bit chunks into chunks of 6 bits by simply re-grouping the digits.


2 Answers

Best you can do is try to decode it. If the decode fails then the input was not base64 encoded. It the string successfully decodes then the input might have been base64 encoded.

like image 183
David Heffernan Avatar answered Sep 28 '22 08:09

David Heffernan


You can check if the string only contains Base64 valids chars

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;

The = char is used for padding so you can add an aditional valiation to the function for padded base64 strings checking if the length of the string is mod 4

like image 25
RRUZ Avatar answered Sep 28 '22 10:09

RRUZ