Autenticação e assinaturas criptográficas
Segurança de requisições com HMAC-SHA256, timestamps e proteção contra repetição.
Para assegurar máxima integridade em produção, o SmallPict requer assinaturas HMAC-SHA256 em requisições de mutação, impedindo adulterações em trânsito e mitigando ataques de repetição.
Cabeçalhos HTTP necessários
| Cabeçalho | Tipo | Descrição |
|---|---|---|
X-API-Key | String | Sua chave pública de API (sp_live_... ou sp_test_...). |
X-Timestamp | Integer | Timestamp Unix em segundos UTC (ex: 1716301234). |
X-Signature | String | Assinatura HMAC-SHA256 codificada em hexadecimal. |
Algoritmo de assinatura
A assinatura é gerada combinando sua Secret Key com a seguinte cadeia canônica:
CANONICAL_STRING = HTTP_METHOD + "\n" + REQUEST_PATH + "\n" + TIMESTAMP + "\n" + SHA256_HEX(REQUEST_BODY)Atenção: O valor enviado em
X-Timestampdeve estar dentro de uma janela de ±300 segundos (5 minutos) do relógio dos servidores SmallPict. Requisições fora deste limite serão rejeitadas com erro401 Unauthorized.
Exemplos de implementação
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))}