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)?
Asked
Active
Viewed 7,003 times
0
-
1http://stackoverflow.com/q/8571501/2427291 – PrR3 Aug 19 '14 at 11:02
-
For a file with 3lakh lines, we cannot chech for each and every indivdual line using string pattern weather it is base 64 encoded or not. – Sany K Singh Aug 19 '14 at 11:22
2 Answers
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.
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