MessageDigestMessage Digest returning different key after first digest

Tags: , , , ,

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");
        } 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)


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


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


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.

Source: stackoverflow