-1

What I have done is, I have created two files - one (message.txt) has the message "hello!", and I have created its Messagedigest and stored it in second file (md.txt). Now I am trying to create a program where it accepts both the message and its md, creates a new md for the message and compares the md to check whether the message is manipulated or not. here's the code:

//getting the original md
            String omd="";
            FileReader fr= new FileReader("D:\\Ns\\md.txt");
            BufferedReader br= new BufferedReader(fr);
            while((omd=br.readLine())!=null)
            {
                System.out.println("original md:"+omd);
            }

    //creating md of the file
    MessageDigest md= MessageDigest.getInstance("MD5");
    FileInputStream file =new FileInputStream("D:\\Ns\\message.txt");
    byte[] dataBytes= new byte[1024];
    int nread=0,nread1;
    while((nread=file.read(dataBytes))!=-1)
    {
        md.update(dataBytes,0,nread);

    }
    byte[] mdbytes=md.digest();
    StringBuffer sb= new StringBuffer();
    for(int i=0; i<mdbytes.length; i++)
    {
        sb.append(Integer.toString((mdbytes[i]& 0xff)+0x100, 16).substring(1));
    }
    String nmd=sb.toString();
    System.out.println("md  created:"+nmd);


    //comparing both
    if(nmd.equals(omd))
    {
        System.out.println("the file is not manipulated!!");
    }
    else{
        System.out.println("the file is manipulated!!");
    }

There are no errors and the code is running, and when I manipulate the message in the file, it shows that it is manipulated. But even when it is not manipulated and both the mds are the same, it shows the message is manipulated.

here is the output:

original md:61c1ec2a71e1e72d95ca5a37589dbff3
md  created:61c1ec2a71e1e72d95ca5a37589dbff3
the file is manipulated!! 

why so? what am I doing wrong here?

Jagger
  • 10,350
  • 9
  • 51
  • 93
Juhi Davda
  • 113
  • 1
  • 1
  • 8
  • 4
    The first loop reads all the lines until `omd` is null. So, when you leave that loop, `omd` is... null. Seriously, now is the best time to learn using your debugger. Such problems are trivial to find when using a debugger, and it's really not complicated. Use it. – JB Nizet Sep 25 '15 at 06:56
  • possible duplicate of [What is a debugger and how can it help me diagnose problems](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Sep 25 '15 at 08:38

1 Answers1

0

You don't need while loop to read the md5 hash file. Because it store only one line. Simple read it like this. Because when the while loop exit, your omd variable have null. That was the terminating condition for while loop.

omd=br.readLine();

And you are comparing nmd with null, so it is false.

if(nmd.equals(null))   ---> This is false.
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73