0

I am trying to calculate a hash based on a rounded value of the system time to allow me time to input the value on another device and check that it's the same hash. When I run the code, it shows me that localTime variable has the same value but i get different values for the digest and can't figure out why.

public static String getTime()
{

    String localTime = "";

    Calendar cal = Calendar.getInstance();

    long mins = cal.getTimeInMillis()/10000;

    localTime = Long.toString(mins);
    System.out.println(localTime);
    byte [] digest = null;
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");

        md.update(localTime.getBytes());
        digest = md.digest();
        md.reset();

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return digest.toString();

}

1 Answers1

1

The problem is the last line. If you return digest.toString(), you are returning the String representation of your byte array (which looks something like [B@12345678]). If you really want to build a String from the byte[], I would strongly suggest you Base64 encode your array:

return new String(Base64.encode(digest));

You'll find Base64 as part of Java8, if you're using something older, you'll find one in Apache codec, Spring utils, etc....

mprivat
  • 20,572
  • 4
  • 51
  • 62
  • It worked! didn't really understand why but i'll figure it out later. Thanks a lot – user3611942 May 07 '14 at 11:55
  • Why they just didn't override the default toString() in arrays is one of the great mysteries in the Java platform. Here's a nice enumeration of common mistakes. http://stackoverflow.com/questions/7281469/why-is-java-util-observable-not-an-abstract-class/7284322#7284322. – mprivat May 07 '14 at 13:03
  • As a side note, I think there's a flaw in your algorithm. Because if you happen to generate your hash at the end of the second, the recipient might be on the next second by the time it gets your message. Not sure what exactly you are trying to achieve but that's just something worth mentioning because you will get intermittent hash recognition failures. – mprivat May 07 '14 at 13:05