Xác thực HMAC-SHA256

Xác thực webhook HiTechCloud Pay bằng HMAC-SHA256: ký từng yêu cầu, kiểm tra chữ ký và timestamp để chống giả mạo và tấn công phát lại (replay).

Xem Markdown

HMAC-SHA256 là phương thức được khuyến nghị cho mọi hệ thống Production. HiTechCloud Pay ký nội dung thô của request bằng khóa bí mật chung, giúp bạn xác minh request thực sự đến từ HiTechCloud Pay và dữ liệu không bị sửa đổi trên đường truyền.

Hai header được gửi kèm

HeaderÝ nghĩa
X-HiTechCloud-SignatureChữ ký số có định dạng sha256={hex_hash}.
X-HiTechCloud-TimestampThời điểm gửi webhook tính bằng Unix Timestamp (giây).

Công thức tạo chữ ký

  1. Lấy giá trị timestamp từ header X-HiTechCloud-Timestamp.
  2. Ghép chuỗi ký theo định dạng {timestamp}.{raw_body} — dùng raw body gốc (chuỗi byte nguyên bản), không parse rồi serialize lại.
  3. Tính HMAC-SHA256 trên chuỗi ký với khóa bí mật SECRET_KEY của webhook.
  4. So sánh kết quả với header X-HiTechCloud-Signature bằng hàm so sánh an toàn thời gian (constant-time).
Phải lấy raw body TRƯỚC khi middleware JSON parse nó. Nếu bạn parse rồi JSON.stringify lại, thứ tự khóa và khoảng trắng có thể đổi khiến chữ ký không khớp.
Kiểm tra chữ ký HMAC-SHA256 bằng PHP
<?php
$signature = $_SERVER['HTTP_X_HITECHCLOUD_SIGNATURE'] ?? '';
$timestamp = (int)($_SERVER['HTTP_X_HITECHCLOUD_TIMESTAMP'] ?? 0);
$raw_body  = file_get_contents('php://input');
$secret    = getenv('HITECHCLOUD_WEBHOOK_SECRET');

// 1. Chống Replay Attack: timestamp lệch quá 300 giây -> từ chối
if (abs(time() - $timestamp) > 300) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Timestamp expired']);
    exit;
}

// 2. Tái tạo chữ ký
$signed_payload = $timestamp . '.' . $raw_body;
$expected = 'sha256=' . hash_hmac('sha256', $signed_payload, $secret);

// 3. So sánh constant-time chống Timing Attack
if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Invalid signature']);
    exit;
}

echo json_encode(['success' => true]);
Kiểm tra chữ ký bằng Node.js (Express, raw body)
const crypto = require('crypto');

// Lưu raw body để ký: express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })
function verifyHiTechCloudWebhook(req, secret) {
  const sig = req.headers['x-hitechcloud-signature'];
  const ts = parseInt(req.headers['x-hitechcloud-timestamp'], 10);
  if (!sig || !ts) return false;

  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - ts) > 300) return false; // chong replay

  const raw = req.rawBody ? req.rawBody.toString('utf8') : JSON.stringify(req.body);
  const expected = 'sha256=' + crypto.createHmac('sha256', secret)
    .update(ts + '.' + raw)
    .digest('hex');

  const a = Buffer.from(sig);
  const b = Buffer.from(expected);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
Kiểm tra chữ ký bằng Python
import hmac, hashlib, time

def verify_hitechcloud_signature(raw_body: bytes, sig_header: str, ts_header: str, secret: str) -> bool:
    if not sig_header or not ts_header:
        return False
    try:
        timestamp = int(ts_header)
    except ValueError:
        return False

    # Chong replay trong 5 phut
    if abs(time.time() - timestamp) > 300:
        return False

    signed = f"{timestamp}.".encode("utf-8") + raw_body
    expected = "sha256=" + hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(sig_header, expected)
Khi chữ ký hợp lệ và timestamp còn hạn, bạn có thể tin tưởng payload và xử lý giao dịch. Vẫn nên kết hợp thêm Idempotency theo trường id để an toàn tuyệt đối.