hello I need a way to read first four bytes of any file using Java. Why the first four bytes? Because it's forensic thumb print of the actual file type (File extension not reliable as it can be falsified)
http://en.wikipedia.org/wiki/File_carving
Now, reading a file this way (below, Java code) will read the file "content", I think it skips file header information...? I can't get the Magic Number (first four bytes) and thus unable to identify/confirm the true file type of a given specimen.
byte[] buffer = new byte[4];
InputStream is = new FileInputStream("somwhere.in.the.dark");
if (is.read(buffer) != buffer.length) {
// do something
}
is.close();
Read First 4 Bytes of File
Suggestion please?
As Blank suggested, https://tika.apache.org
Here's the code - in this example, "test3_iamexe.txt" is an executable, with file extension renamed to "txt" by attacker.
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.parser.AbstractParser;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.XHTMLContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Set;
import org.apache.tika.metadata.Property;
public class TestTika {
public static void main(String[] args) {
File file = null;
InputStream stream = null;
String contentType = null;
try
{
file = new File("C:\\tmp\\test3_iamexe.txt");
stream = new FileInputStream(file);
AutoDetectParser parser = new AutoDetectParser();
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
try {
// This step here is a little expensive
parser.parse(stream, handler, metadata);
} finally {
stream.close();
}
// metadata is a HashMap, you can loop over it see what you need. Alternatively, I think Content-Type is what you need
contentType = metadata.get("Content-Type");
} catch(...)
{
// handle it
}
return;
}
}
I think you can use:
IOUtils.toByteArray(InputStream is)
See here : IOUtils.toByteArray to convert your InputStream to a byteArray, then get the first 4 bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With