[Java] [Snippet] Verify File Signatures
#1
Following code shows two ways to verify file signatures (Magic Number). I hope the code is readable enough. If you need more explanation then reply to the thread.

Code:
package net.letshackit.corejava;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/**
*
*/
public class MagicNumberChecker {

   /**
    * Default Constructor
    */
   public MagicNumberChecker() {
   }

   public boolean verifyFileHeader(File file, int[] magicNumber) {
       try(FileInputStream fis = new FileInputStream(file)) {
           for (int i : magicNumber) {
               if (fis.read() != i) {
                   return false;
               }
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
       return true;
   }

   public boolean verifyFileHeader(File file, byte[] magicNumber) {
       try(FileInputStream fis = new FileInputStream(file)) {
           byte[] buffer = new byte[magicNumber.length];
           if(fis.read(buffer) != -1) {
               return Arrays.equals(magicNumber, buffer);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
       return false;
   }

   public static void main(String... strings) {

       final int[] SQLITE3_MAGIC_HEADER = {
               0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74,
               0x20, 0x33, 0x00
       };

       final byte[] SQLITE3_MAGIC_HEADER2 = {
               (byte) 0x53, (byte) 0x51, (byte) 0x4c, (byte) 0x69, (byte) 0x74, (byte) 0x65,
               (byte) 0x20, (byte) 0x66, (byte) 0x6f, (byte) 0x72, (byte) 0x6d, (byte) 0x61,
               (byte) 0x74, (byte) 0x20, (byte) 0x33, (byte) 0x00
       };

       MagicNumberChecker mnc = new MagicNumberChecker();

       File file = new File(mnc.getClass().getResource("resources/test.db").getFile());

       if (mnc.verifyFileHeader(file, SQLITE3_MAGIC_HEADER)) {
           System.out.println("Valid Sqlite3 Database!");
       } else {
           System.out.println("Invalid Sqlite3 Database!");
       }

       if (mnc.verifyFileHeader(file, SQLITE3_MAGIC_HEADER2)) {
           System.out.println("Valid Sqlite3 Database!");
       } else {
           System.out.println("Invalid Sqlite3 Database!");
       }
   }
}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Java sockets 0xRar 3 8,759 12-24-2020, 12:36 PM
Last Post: 0xRar
  Useful resources to become a better Java programmer LOSTINSAUCE 2 14,369 12-21-2020, 09:41 AM
Last Post: 0xRar
  Java won't work properly QMark 2 12,261 02-12-2019, 12:25 AM
Last Post: QMark
  Words with friends(Cheat) Java ImArtisan 0 10,172 03-15-2018, 10:35 AM
Last Post: ImArtisan