質問

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();

}
役に立ちましたか?

解決

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top