MessageDigest isEqual Compares Digests
Compare MACs and hashes with MessageDigest.isEqual, whose constant-time scan avoids the early-exit leak that Arrays.equals has.
Code
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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.