Search code examples
javabufferedreaderstring-comparisonmessage-digest

I am comparing return value of BufferedReader.readLine() and a string, but it's not working


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?


Solution

  • 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.