Write a C Program to Recovers JPEGs from a forensic image ?
Solution:
/* Recovers JPEGs from a forensic image. */
#include <stdio.h>
#include <stdint.h>
// Makes the possibility to create a byte array
typedef uint8_t BYTE;
//start
int main(int argc, char* argv[])
{
//creates a buffer to store the image data
BYTE buffer[512];
//open card.raw
FILE *card = fopen("card.raw","r");
//chekc if card is null
if(card == NULL){
printf("cannot open file");
return 2;
}
//will count the number of images encountered
int filecount = 0;
//creates the img FILE outside the while (to avoid the scope)
FILE *img = NULL;
//creates an array for the name of file (to avoid scope)
char name[8];
//while we can read the file
while(fread(&buffer, 512, 1, card)){
//if the jpg signature is found in file
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&
(buffer[3] == 0xe1 || buffer[3] == 0xe2 || buffer[3] == 0xe3 ||
buffer[3] == 0xe4 || buffer[3] == 0xe5 || buffer[3] == 0xe6 ||
buffer[3] == 0xe7 || buffer[3] == 0xe0 || buffer[3] == 0xe8 ||
buffer[3] == 0xe9 || buffer[3] == 0xea || buffer[3] == 0xeb ||
buffer[3] == 0xec || buffer[3] == 0xed || buffer[3] == 0xef ) ){
//if the image is already open, close it
if(img != NULL){
fclose(img);
}
//just make this for the naming the file
if(filecount <= 9){
sprintf(name, "00%d.jpg", filecount);
} else if (filecount >= 10){
sprintf(name,"0%d.jpg",filecount);
}
//open the file
img = fopen(name, "w");
//check if we can open it
if (img == NULL){
return 3;
}
//increments the file counter
filecount++;
//writes the first 512 bytes to file
fwrite(&buffer, 512, 1, img);
} else{
// if an image is already open, close it
if(img)
fclose(img);
//and reopen to ensure we are writing in the same file over the time
img = fopen(name, "w");
//write to file
fwrite(&buffer, 512, 1, img);
}
}
//close pointers
fclose(card);
fclose(img);
//Be happy!
return 0;
}