0

The first program should take two inputs as arguments: directory1 and directory2. the program should compute a hash value (using HMAC) for each file in the folder directory1 and store that hash value in a new file that will be saved under the folder directory2. (b). The second program should perform the verification process. It also takes the same two input arguments as the first program. It should generate hashes again (you can reuse some code from the first program here) and check whether they are matching with the corresponding values stored in directory2. For each file, this program should output two strings: the filename and YES/NO (denoting whether the hashes matched or not)

i have done some work which will generate hash value of a single file from one folder and i need help in generating hash value of all files from that folder these are the codes as follows.

Function

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.security.MessageDigest;

public class HMAC {

public static void main(String args[]) throws Exception {


  String datafile = "/Users/Samip/Desktop/crypto1";

MessageDigest md = MessageDigest.getInstance("SHA1");
FileInputStream fis = new FileInputStream(datafile);
byte[] dataBytes = new byte[1024];

int nread = 0; 

while ((nread = fis.read(dataBytes)) != -1) {
  md.update(dataBytes, 0, nread);
};

byte[] mdbytes = md.digest();

//convert the byte to hex format
StringBuffer sb = new StringBuffer("");



for (int i = 0; i < mdbytes.length; i++) {
    sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}

//System.out.println("SHA-1 value is :: " + sb.toString());





    FileWriter file = new FileWriter("/Users/Samip/Desktop/crypto/output.txt");
    PrintWriter output = new PrintWriter(file);
    output.println(sb.toString());    
    output.close(); 
    System.out.println(sb.toString());

 }
 }

i hope someone can help me with this.

Raju
  • 11
  • 5
  • With what exactly? Please ask a question. – Jan Dec 03 '15 at 19:29
  • i want to generate a text file which has got all hash values of all random files in a particular folder. i have a function for a single file i need to implement it for whole folder. – Raju Dec 03 '15 at 19:46
  • So for each file, you want one hash written to file. And you already have code for **one** file. And File.listFiles() can list all Files in a directory. So where's the exact question / error / problem you're facing? – Jan Dec 03 '15 at 19:48
  • i need to generate hash for all the files, i just know how to generate for one file. – Raju Dec 03 '15 at 20:11
  • string datafile can only select one file at a time need some help with selecting whole folder. – Raju Dec 03 '15 at 20:13
  • see my answer for a way to patch this together. – Jan Dec 03 '15 at 20:19
  • everything is getting more and more complicated, now i have three methods as you suggested but i don't know what can i do for my main method.. – Raju Dec 03 '15 at 21:19

2 Answers2

0

You can use this to iterate over all files and use your hash function on it. Store your results in a file separating them with \n (line break)

String stringout = "" 
Files.walk(Paths.get("/path/to/dir1")).forEach(filePath -> { 
    if (Files.isRegularFile(filePath)) { 
        //create your hash 
        stringout += hash + "\n" 
    }
});
// write stringout to your output file 

For the second program you can reuse that code and read your hashes from the file using this. Then split them by \n to get your hashes and compare them to the output of your hash function.

Community
  • 1
  • 1
Niklas
  • 375
  • 1
  • 3
  • 17
0

Basic Layout / Top-Down Approach

Start with what you know and put that into methods. You start with names and the stuff they need to perform. Don't think about implementation for a second, just about the flow of logic.

In your case, you'll need something like:

public void createHash(File sourceDir, File targetDir)

public String createHash(File file)

public void writeHash(File toFile, String hash)

Wrap it in main()

You need to fill in your class-name there.

public static void main(String[] args) {
   new YourClass().createHash(new File(args[0]), new File(args[1]));
}

Implement Top-Down

Start with the outermost method and try to get that right. You can start with dummy code for the rest.

public void createHash(File sourceDir, File targetDir) {
  for(File f : sourceDir.listFiles()) {
     String hash = createHash(f); //That you almost have
     File target = new File(targetDir, f.getName()+".hash");
     writeHash(target, hash);
  } 
}

public String createHash(f) {
  return f.getName(); //This is where your existing code will go later
}

public String writeHash(File target, String hash) {
  System.out.println("I'd write " + hash + " to File " + file.getName());
}

Now your program should be able to iterate through source folder, create (dummy) hashes and print to System.out what files it would write.

Refine methods

Now do the rest step by step - one method at a time. Until you're done or something breaks - in which case you come back for help.

  public String createHash(File datafile) throws IOException {
    //SNIP - YOUR CODE BEGINS
    MessageDigest md = MessageDigest.getInstance("SHA1");
    FileInputStream fis = new FileInputStream(datafile);
    byte[] dataBytes = new byte[1024];

    int nread = 0; 

    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    }

    byte[] mdbytes = md.digest();

    //convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) {
      sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
  //SNAP - YOUR CODE ENDS
  }
  public void writeFile(File target, String hash) {
     try(FileOutputStream fo = new FileOutputStream(target)) {
       fo.write(hash.getBytes());
     } catch(IOException e) {
       System.err.println("No Hash Written for " + target.getName());
     }
  }

Working Example

import java.io.*;
import java.security.MessageDigest;

public class Checksums {

    public static void main(String[] args) {
        String sourceDir = "/Users/Jan/Desktop/Folder1";
        String targetDir = "/Users/Jan/Desktop/Folder2";
        try {
            new Checksums().createHash(new File(sourceDir), new File(targetDir));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createHash(File sourceDir, File targetDir) throws Exception {
        for (File f : sourceDir.listFiles()) {
            String hash = createHash(f); // That you almost have
            File target = new File(targetDir, f.getName() + ".hash");
            writeHash(target, hash);
        }
    }

    public String createHash(File datafile) throws Exception {
        // SNIP - YOUR CODE BEGINS
        MessageDigest md = MessageDigest.getInstance("SHA1");
        FileInputStream fis = new FileInputStream(datafile);
        byte[] dataBytes = new byte[1024];

        int nread = 0;

        while ((nread = fis.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        }

        byte[] mdbytes = md.digest();

        // convert the byte to hex format
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        // SNAP - YOUR CODE ENDS
        return sb.toString();
    }

    public void writeHash(File target, String hash) {
        try (FileOutputStream fo = new FileOutputStream(target)) {
            fo.write(hash.getBytes());
            System.out.println("Hash written for " + target.getAbsolutePath());
        } catch (IOException e) {
            System.err.println("No Hash Written for " + target.getName());
        }
    }

}
Jan
  • 13,738
  • 3
  • 30
  • 55