認証に HMAC を使う方法
HMAC 署名を生成・検証して、メッセージと API リクエストを認証します。
问题
メッセージや API リクエストが共有秘密鍵を知る者によって送信されたこと、および転送中に改ざんされていないことを証明する必要があります。
前提条件
- ハッシュ関数の理解
- 共有秘密鍵に関する知識
ステップ
-
1. Prepare the message and key
Define the message to authenticate (e.g., an API request body or a timestamp + payload). Agree on a secret key with the other party. The key should be at least as long as the hash output (32 bytes for HMAC-SHA256).
入力message: 'payload' | key: 'secret'输出ready to sign -
2. Compute the HMAC
Run HMAC-SHA256 with the key and message. HMAC wraps the hash function with key mixing, producing a tag that only someone with the key can compute. The tag is typically sent as a hex or Base64 string alongside the message.
入力HMAC-SHA256(key, message)输出tag: a1b2c3... -
3. Verify on the receiving end
The recipient recomputes the HMAC with the same key and message and compares it to the received tag using a constant-time comparison. If they match, the message is authentic and unmodified. If they differ, reject the message.
入力recomputed tag == received tag输出verified ✓
期待される結果
メッセージの送信元と整合性を認証する HMAC タグ。共有鍵を持つ誰もが検証できます。
よくあるエラー
- Comparing tags with a non-constant-time comparison
- Use a constant-time comparison (e.g., crypto.timingSafeEqual) to prevent timing attacks that leak the tag byte by byte.
- Including the key in the message
- The key is never sent. Only the message and the HMAC tag are transmitted. The key stays on both sides.
トラブルシューティング指引
- If verification fails, check that the message is byte-identical on both sides (no encoding differences).
- Include a timestamp or nonce in the message to prevent replay attacks.
セキュリティ上の制限
- HMAC security depends on the secrecy of the key and the collision resistance of the underlying hash. Use SHA-256 or stronger.
- All computation is local.