Skip to content
smallPict

المصادقة والتوقيعات الرقمية HMAC-SHA256

تأمين الطلبات عبر HMAC-SHA256 والتحقق من الطوابع الزمنية ومنع هجمات إعادة الإرسال.

لضمان أعلى درجات الأمان في بيئات العمل الحية، تشترط SmallPict توقيع HMAC-SHA256 لكافة الطلبات التعديلية، مما يمنع التلاعب بالبيانات أثناء النقل ويحمي من هجمات الإعادة.


ترويسات HTTP الإلزامية

الترويسةالنوعالوصف
X-API-Keyنصمفتاحك العام لواجهة برمجة التطبيقات (sp_live_... أو sp_test_...).
X-Timestampعدد صحيحطابع Unix الزمني بالثواني بتوقيت UTC (مثال: 1716301234).
X-Signatureنصالتوقيع الرقمي المحسوب بصيغة الست عشري (Hex).

خوارزمية حساب التوقيع الرقمي

يتم إنشاء التوقيع بتطبيق HMAC-SHA256 باستخدام Secret Key الخاص بك على السلسلة المعيارية التالية:

TEXT
CANONICAL_STRING = HTTP_METHOD + "\n" + REQUEST_PATH + "\n" + TIMESTAMP + "\n" + SHA256_HEX(REQUEST_BODY)

تنبيه هام: يجب ألا ينحرف الطابع الزمني في X-Timestamp عن توقيت خوادم SmallPict بأكثر من ±300 ثانية (5 دقائق)، وإلا سيتم رفض الطلب برمز 401 Unauthorized.


نماذج برمجية لحساب التوقيع

Node.js / TypeScript

TypeScript
import crypto from "crypto";
function generateSignature(method: string, path: string, timestamp: number, body: string, secretKey: string): string {  const bodyHash = crypto.createHash("sha256").update(body).digest("hex");  const canonical = `${method.toUpperCase()}\n${path}\n${timestamp}\n${bodyHash}`;  return crypto.createHmac("sha256", secretKey).update(canonical).digest("hex");}

Python

Python
import hmac, hashlib
def generate_signature(method: str, path: str, timestamp: int, body: bytes, secret_key: str) -> str:    body_hash = hashlib.sha256(body).hexdigest()    canonical = f"{method.upper()}\n{path}\n{timestamp}\n{body_hash}"    return hmac.new(secret_key.encode('utf-8'), canonical.encode('utf-8'), hashlib.sha256).hexdigest()

Golang

Go
package main
import (    "crypto/hmac"    "crypto/sha256"    "encoding/hex"    "fmt"    "strings")
func GenerateSignature(method, path string, timestamp int64, body []byte, secretKey string) string {    bodyHash := sha256.Sum256(body)    canonical := fmt.Sprintf("%s\n%s\n%d\n%s", strings.ToUpper(method), path, timestamp, hex.EncodeToString(bodyHash[:]))    mac := hmac.New(sha256.New, []byte(secretKey))    mac.Write([]byte(canonical))    return hex.EncodeToString(mac.Sum(nil))}