Authentification et signatures cryptographiques
Sécurité des requêtes avec HMAC-SHA256, horodatages et prévention du rejeu.
Pour une protection maximale en environnement de production, SmallPict exige une signature cryptographique HMAC-SHA256 sur chaque requête modificatrice, empêchant l'altération de données et bloquant les attaques par rejeu.
En-têtes HTTP requis
| En-tête | Type | Rôle |
|---|---|---|
X-API-Key | Chaîne | Votre clé publique d'API (sp_live_... ou sp_test_...). |
X-Timestamp | Entier | Horodatage Unix en secondes UTC (ex. 1716301234). |
X-Signature | Chaîne | Empreinte calculée en HMAC-SHA256 au format hexadécimal. |
Algorithme de calcul de la signature
La signature résulte du calcul HMAC-SHA256 de votre Secret Key sur la chaîne canonique suivante :
CANONICAL_STRING = HTTP_METHOD + "\n" + REQUEST_PATH + "\n" + TIMESTAMP + "\n" + SHA256_HEX(REQUEST_BODY)Attention : La valeur renseignée dans
X-Timestampdoit se situer dans un intervalle de ±300 secondes (5 minutes) par rapport à l'heure des serveurs SmallPict. Tout écart supérieur entraîne un rejet immédiat avec le code401 Unauthorized.
Exemples d'implémentation
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))}