Autenticazione e firme crittografiche
Sicurezza delle richieste con HMAC-SHA256, timestamp e prevenzione da attacchi replay.
Per garantire la massima integrità in ambiente di produzione, SmallPict impone una firma crittografica HMAC-SHA256 per ciascuna richiesta mutativa, prevenendo manomissioni e attacchi di tipo replay.
Intestazioni HTTP obbligatorie
| Intestazione | Tipo | Funzione |
|---|---|---|
X-API-Key | Stringa | La tua chiave API pubblica (sp_live_... o sp_test_...). |
X-Timestamp | Intero | Timestamp Unix in secondi UTC (es. 1716301234). |
X-Signature | Stringa | Firma calcolata in HMAC-SHA256 in formato esadecimale. |
Algoritmo di calcolo della firma
La firma si ottiene applicando HMAC-SHA256 con la tua Secret Key sulla seguente stringa canonica:
CANONICAL_STRING = HTTP_METHOD + "\n" + REQUEST_PATH + "\n" + TIMESTAMP + "\n" + SHA256_HEX(REQUEST_BODY)Avviso: Il timestamp indicato in
X-Timestampdeve rientrare in un margine di tolleranza di ±300 secondi (5 minuti) rispetto all'orologio dei server SmallPict. Discrepanze maggiori causeranno un rifiuto immediato con errore401 Unauthorized.
Esempi di implementazione
Node.js / 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
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
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))}