实现说明
除了类 PayloadSigner,文件里再无其他定义。
使用要点
- 每一步打印都带着自己的标签:
signature:、verify ok:、tamper detected:。
常见问题
运行「HMAC-SHA256 签名与校验」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 signature:、verify ok:、tamper detected: 这类标签。
核心语句
byte[] key = "rotate-me-quarterly-demo-key".getBytes(StandardCharsets.UTF_8);
mac.init(new SecretKeySpec(key, "HmacSHA256"));
Mac mac = Mac.getInstance("HmacSHA256");
代码示例
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class PayloadSigner {
public static void main(String[] args) throws Exception {
// Hard-coded key for demonstration only; real systems inject it from a secret manager or env
byte[] key = "rotate-me-quarterly-demo-key".getBytes(StandardCharsets.UTF_8);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
String payload = "order=1001&amount=42";
String signature = HexFormat.of().formatHex(
mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
System.out.println("signature: " + signature);
// After doFinal the Mac resets to its init state: the same key can compute another tag right away
String replay = HexFormat.of().formatHex(
mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
System.out.println("verify ok: " + replay.equals(signature));
// Change one character of the payload and the tag no longer matches
String tampered = HexFormat.of().formatHex(
mac.doFinal("order=1001&amount=43".getBytes(StandardCharsets.UTF_8)));
System.out.println("tamper detected: " + !tampered.equals(signature));
}
}