MessageDigest isEqual Compares Digests

Compare MACs and hashes with MessageDigest.isEqual, whose constant-time scan avoids the early-exit leak that Arrays.equals has.

JavaAuth Jwt

Code

snippet
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class TamperCheck {

    static byte[] sha256(byte[] data) throws NoSuchAlgorithmException {
        return MessageDigest.getInstance("SHA-256").digest(data);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        byte[] payload = "order:42|total:1990".getBytes(StandardCharsets.UTF_8);
        byte[] expected = sha256(payload);

        // 攻击者篡改总量后重算请求:摘要对不上
        byte[] tamperedPayload =
                "order:42|total:999999".getBytes(StandardCharsets.UTF_8);
        byte[] received = sha256(tamperedPayload);

        // isEqual 是恒时比较:扫描全部字节,耗时只取决于第一个数组长度,
        // 不会在第一个不一致字节处提前返回(Arrays.equals 会提前退出)
        boolean matches = MessageDigest.isEqual(expected, received);
        System.out.println("tampered matches: " + matches);

        // 完整性成立时两个摘要逐字节一致
        byte[] honest = sha256(payload);
        System.out.println("honest matches: " + MessageDigest.isEqual(expected, honest));
        System.out.println("Arrays.equals agrees: " + Arrays.equals(expected, honest));

        // 长度不同直接判 false,无需逐字节比较
        System.out.println("short digest vs full: "
                + MessageDigest.isEqual(expected, Arrays.copyOf(expected, 8)));
    }
}

How the logic moves

MessageDigest isEqual Compares Digests is built around the class TamperCheck.

Watch out for

  • The project needs no additions before it runs.

Using it

Output lines are prefixed (tampered matches:, honest matches:, Arrays.equals agrees:), which surfaces what every step changed.

Statements in the spotlight

return MessageDigest.getInstance("SHA-256").digest(data);

Interactive Tools for This Topic

FAQ

What does MessageDigest isEqual Compares Digests print when run?
The script runs standalone; its 4 labeled outputs include `tampered matches:`, `honest matches:`, `Arrays.equals agrees:`.