We can validate a base64 encoded string using a nice regex (regular expression). The following regex can be used with any programming language. I would use php for the example. The regex is as follows.
^[a-zA-Z0-9/+]*={0,2}$
Which will also detect the usage of = or == at the end of the string (and only end).
A function geared specifically toward this:
<?phpfunction is_base64_encoded() { if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) { return TRUE; } else { return FALSE; } }; is_base64_encoded("iash21iawhdj98UH3"); // true is_base64_encoded("#iu3498r"); // false is_base64_encoded("asiudfh9w=8uihf"); // false is_base64_encoded("a398UIhnj43f/1!+sadfh3w84hduihhjw=="); // false ?>
Can you explain this regex match for the last one?
I haven’t used the php variant of re but I’ve used them extensively on bash and python.
According to my understating (and it does fail in bash) the last test case should fail.
Sorry that was mistake the last example is invalid base64 so should return false