MD5 on same file gives different hash

Can someone tell me what is wrong with this code? Each time I use it on the same file, it gives a different hash code :confused:


	public static byte[] generateHash(String file)
	{
		InputStream is;
		try
		{
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			is = new FileInputStream(file);
			is = new DigestInputStream(is, algorithm);
			is.close();
			return algorithm.digest();
		} 
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

Where do you read the contents of the file?

hmm… you are right.
What about this? the same thing is still happening.


	public static byte[] GenerateHash(String file)
	{
		InputStream is;
		try
		{
			MessageDigest algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			is = new FileInputStream(new File(file));
			
			byte[] bytes = new byte[1024];
			 
		    int read = 0;
		    while ((read = is.read(bytes)) != -1) {
		    	algorithm.update(bytes, 0, read);
		    };
		    is.close();
		    
		    byte[] digest = algorithm.digest();
			
			return digest;
		} 
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

Oops ;D the second version does work. I was printing out the hash wrong System.out.println(bytes) instead of System.out.println(new String(bytes))
Thanks :slight_smile: