HMAC (Hash-based Message Authentication Code) คืออะไร?
HMAC = Hash-based Message Authentication Code เป็นกลไกยืนยัน ความสมบูรณ์ (Integrity) และ ความถูกต้อง (Authenticity) ของข้อความ ใช้ Hash Function (เช่น SHA-256) ร่วมกับ Secret Key
HMAC vs MAC vs Hash
| ประเภท | Key | วัตถุประสงค์ | ตัวอย่าง |
| Hash (SHA-256) | ไม่มี | Integrity เท่านั้น (ไม่มี Authenticity) | File Checksum |
| MAC (CBC-MAC, CMAC) | Secret Key | Integrity + Authenticity | AES-CMAC |
| HMAC | Secret Key | Integrity + Authenticity (แยก Key/Message Hashing) | HMAC-SHA256, HMAC-SHA1 |
ทำไม HMAC ปลอดภัยกว่า MAC แบบเดิม?
- แยก Hash Key และ Message → กัน Length Extension Attacks
- ความปลอดภัยขึ้นอยู่กับ: Hash Function Strength, Key Length, Output Length
- HMAC-SHA256 กับ Key 256-bit = ปลอดภัยทางทฤษฎี (Brute-force ไม่ได้)
การทำงานของ HMAC (RFC 2104)
HMAC(K, m) = H((K' ⊕ opad) || H((K' ⊕ ipad) || m))
K' = Key padded ให้ยาวเท่า Block Size (64 bytes สำหรับ SHA-256)
ipad = 0x36 ซ้ำ, opad = 0x5C ซ้ำ
|| = Concatenation
การใช้งาน HMAC ใน Network Security
- API Authentication: AWS Signature v4, Azure, Google Cloud (HMAC-SHA256)
- JWT (JSON Web Tokens): HS256 = HMAC-SHA256
- TLS/SSL: HMAC-based Cipher Suites (HMAC-SHA256)
- IPsec/IKEv2: PRF ใช้ HMAC-SHA256/384/512
- SSH: MAC Algorithms (hmac-sha2-256, hmac-sha2-512)
- Wireless (WPA2/WPA3): PBKDF2 ใช้ HMAC-SHA1, SAE ใช้ HMAC-SHA256
- Message Integrity: Financial Transactions, Firmware Updates, Config Sync
Python HMAC Implementation
import hmac
import hashlib
# Basic Usage
secret_key = b'my-secret-key-256-bit-long!!'
message = b'Important network security data'
# HMAC-SHA256
hmac_obj = hmac.new(secret_key, message, hashlib.sha256)
digest = hmac_obj.digest() # bytes (32 bytes)
hex_digest = hmac_obj.hexdigest() # hex string (64 chars)
# Verify (Constant-time comparison - ป้องกัน Timing Attack)
received_hmac = b'...'
expected_hmac = hmac.new(secret_key, message, hashlib.sha256).digest()
if hmac.compare_digest(received_hmac, expected_hmac):
print("Valid!")
else:
print("Invalid!")
# Streaming (Large Data)
hmac_obj = hmac.new(secret_key, b'', hashlib.sha256)
for chunk in data_stream:
hmac_obj.update(chunk)
final_digest = hmac_obj.digest()
Best Practices
- ✅ ใช้ hmac.compare_digest() ป้องกัน Timing Attack
- ✅ Key Length ≥ Hash Output (SHA-256 → Key ≥ 32 bytes)
- ✅ Rotate Keys เป็นระยะ
- ✅ ใช้ HKDF (HMAC-based Key Derivation) สร้าง Sub-keys
- ❌ อย่าใช้ HMAC-SHA1 (Deprecated)
- ❌ อย่า Hardcode Key ใน Code (ใช้ Vault, KMS, Env Vars)
OpenSSL HMAC
# Command Line
echo -n "message" | openssl dgst -sha256 -hmac "secret-key"
# C API
#include
HMAC(EVP_sha256(), key, key_len, data, data_len, md, &md_len);