प्रमाणीकरण और HMAC-SHA256 डिजिटल हस्ताक्षर
HMAC-SHA256, टाइमस्टैम्प सत्यापन और रीप्ले हमलों से सुरक्षा के माध्यम से सुरक्षित अनुरोध।
उत्पादन परिवेश में पूर्ण सुरक्षा सुनिश्चित करने के लिए, SmallPict प्रत्येक परिवर्तनकारी अनुरोध के लिए HMAC-SHA256 हस्ताक्षर अनिवार्य करता है। यह डेटा से छेड़छाड़ को रोकता है और रीप्ले हमलों को बेअसर करता है।
आवश्यक HTTP हेडर
| हेडर | प्रकार | विवरण |
|---|---|---|
X-API-Key | String | आपकी सार्वजनिक API कुंजी (sp_live_... या sp_test_...)। |
X-Timestamp | Integer | UTC सेकंड में Unix टाइमस्टैम्प (उदा. 1716301234)। |
X-Signature | String | हेक्साडेसिमल प्रारूप में परिकलित HMAC-SHA256 हस्ताक्षर। |
हस्ताक्षर परिकलन एल्गोरिदम
हस्ताक्षर आपके Secret Key का उपयोग करके विहित स्ट्रिंग पर HMAC-SHA256 लागू करके बनाया जाता है:
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))}