Skip to content
Advertisement

MessageDigestMessage Digest returning different key after first digest

Here is how I initialize MessageDigest

private static MessageDigest messageDigest;

    public static final String SALT_DO_NOT_CHANGE = "somesalt";

    static {
        try {
            messageDigest = MessageDigest.getInstance("SHA-512");
            messageDigest.update(SALT_DO_NOT_CHANGE.getBytes());
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("error for message digest", e);
            throw new RuntimeException("could not initialize message digest");
        }
    }

And here is how digest to get bytes for password which I later convert to string (no issue there)

byte[] bytes = messageDigest.digest(password.getBytes(StandardCharsets.UTF_8));

Now assume the password is “Password@1”.

Here is the output first time (apologies for long text below)

115,83,48,-2,41,29,-99,71,-54,-53,-26,-67,-118,48,-75,77,13,100,42,70,-72,110,-85,23,-38,119,-110,-15,121,3,-25,114,-68,109,-108,94,-122,65,-62,10,-90,8,-125,114,-118,51,-51,89,127,55,37,83,-126,56,-31,-27,-49,-60,25,74,-80,-110,23,45

And here is output second time onwards. It remains same after this.

-62,-50,45,-44,91,-86,16,90,85,53,101,-122,51,12,-82,52,-123,-101,-10,-28,-108,114,120,-96,84,-23,38,-75,78,67,36,-93,-88,-11,79,76,126,-34,-2,109,76,-31,-30,-86,-28,13,-91,-22,-65,-128,108,-47,15,19,95,60,-30,-123,-4,20,-64,21,-1,7

Can some one please help me understand what is happening here?

Advertisement

Answer

The static block is only run once, when the class is loaded (or more exactly, initialized, but in practice that happens at load). Thus if you have a method that does messageDigest.digest(password) on the first call it computes the digest of the bytes of somesaltPassword@1 which is your first value, and leaves the messageDigest object reset; any subsequent call computes the digest of the bytes of Password@1 which is your second value, and again leaves it reset.

BTW the entire purpose and reason for using salt is that it does change, plus doing a single fast hash of a password (even with salt) is not secure unless it’s a very high-entropy password (more than a human can remember), but those are offtopic for SO; search security.SX and/or crypto.SX where these have been answered and discussed many times.

Advertisement