0

I want to check whether a .txt/.xml file contains any base64 encoded data in it or not using java? Is there any way to do the file check (like for EBCDIC and UCS-2 where we can check the file type without reading the entire content of the file)?

Sany K Singh
  • 1
  • 1
  • 1

2 Answers2

1

Unfortunately, Base64 doesn't include any special signature which would indicate that the content is Base64-encoded - it's just the encoded data which can have padding.

If you want to check if the whole file or a part of it is Base64-encoded, you are going to have to read the string you want to test and check if it's a valid Base64 using the ways provided in the question linked by @PrR3.

Community
  • 1
  • 1
izstas
  • 5,004
  • 3
  • 42
  • 56
0

You cannot check if a whole file is base64 or not, you can check each string in this file to see if it's encoded base 64. You can use the function below to do that:

public bool IsBase64Encoded(String str)
{
    try
    {
        // If no exception is caught, then it is possibly a base64 encoded string
        byte[] data = Convert.FromBase64String(str);
        // The part that checks if the string was properly padded to the
        // correct length was borrowed from d@anish's solution
        return (str.Replace(" ","").Length % 4 == 0);
    }
    catch
    {
        // If exception is caught, then it is not a base64 encoded string
       return false;
    }
}
mkazma
  • 572
  • 3
  • 11
  • 29
  • I am using pattern for the same. But checking entire file content like this is not feasible. Due to poor performance http://stackoverflow.com/questions/8571501/how-to-check-whether-the-string-is-base64-encoded-or-not – Sany K Singh Aug 19 '14 at 13:31