Hashing & Encoding

7 endpoints for one-way hashing, message authentication, and encoding/decoding.

Method Endpoint Purpose
POST /v1/auth/hash Compute a cryptographic hash (MD5 → BLAKE2b)
POST /v1/auth/hmac Generate an HMAC signature
POST /v1/auth/hmac-verify Verify an HMAC signature (constant-time)
POST /v1/auth/base64-encode Base64 or Base64URL encode a string
POST /v1/auth/base64-decode Decode a Base64 or Base64URL string
POST /v1/auth/encode Encode or decode in multiple formats
POST /v1/auth/spam-score Score a form submission for spam likelihood

Python SDK Examples

Compute a cryptographic hash

hash supports all commonly used algorithms. SHA-256 is the modern general-purpose default. MD5 and SHA-1 are available for compatibility (e.g., computing S3 ETags or legacy checksums) but should not be used for security purposes.

from toolkitapi import Auth

auth = Auth(api_key="tk_...")

# SHA-256 — general purpose
result = auth.hash("Hello, world!", algorithm="sha256")
print(result["hash"])
# 315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3

# SHA3-256 — next-generation, resistant to length-extension attacks
result = auth.hash("Hello, world!", algorithm="sha3-256")
print(result["hash"])

# BLAKE2b — fastest secure hash, suitable for checksums of large data
result = auth.hash("Hello, world!", algorithm="blake2b")
print(result["hash"])

# MD5 — legacy only (e.g., Gravatar identicons, ETag matching)
md5 = auth.hash("[email protected]", algorithm="md5")
print(md5["hash"])

Hash file contents for integrity verification

from toolkitapi import Auth

auth = Auth(api_key="tk_...")

def hash_file(path: str, algorithm: str = "sha256") -> str:
    """Return the hex hash of a file for integrity checking."""
    with open(path, "rb") as f:
        content = f.read().decode("utf-8", errors="replace")
    result = auth.hash(content, algorithm=algorithm)
    return result["hash"]

Generate an HMAC signature

HMAC adds a secret key to a hash — it proves both integrity (not tampered) and authenticity (came from someone who knows the key). Use it for webhook payload signing, API request signing, and secure cookies.

from toolkitapi import Auth

auth = Auth(api_key="tk_...")

WEBHOOK_SECRET = "whsec_xK9mQ..."

def sign_webhook_payload(payload: str) -> str:
    """Return the HMAC-SHA256 hex signature for a webhook payload."""
    result = auth.hmac(payload, key=WEBHOOK_SECRET, algorithm="sha256")
    return result["hmac"]

# Sign outgoing webhook
import json
body = json.dumps({"event": "payment.completed", "amount": 9900})
signature = sign_webhook_payload(body)
# Set header: X-Signature: sha256=<signature>

Verify an HMAC signature

hmac_verify uses constant-time comparison, which prevents timing attacks that would allow an attacker to guess the signature one byte at a time.

from toolkitapi import Auth

auth = Auth(api_key="tk_...")

WEBHOOK_SECRET = "whsec_xK9mQ..."

def verify_webhook(raw_body: str, received_signature: str) -> bool:
    """
    Verify an incoming webhook payload signature.

    Parameters
    ----------
    raw_body : str
        The raw request body (before any JSON parsing).
    received_signature : str
        The hex signature from the X-Signature header (strip any 'sha256=' prefix).
    """
    result = auth.hmac_verify(
        message=raw_body,
        key=WEBHOOK_SECRET,
        signature=received_signature,
        algorithm="sha256",
    )
    return result["valid"]

Base64 encode and decode

from toolkitapi import Auth

auth = Auth(api_key="tk_...")

# Standard Base64 — for email attachments, PEM data, Basic Auth headers
encoded = auth.base64_encode("Hello, world!")
print(encoded["encoded"])    # SGVsbG8sIHdvcmxkIQ==
print(encoded["encoding"])   # base64

decoded = auth.base64_decode("SGVsbG8sIHdvcmxkIQ==")
print(decoded["decoded"])    # Hello, world!

# URL-safe Base64 — for JWT payloads, URL parameters, filenames
url_encoded = auth.base64_encode("Hello, world!", url_safe=True)
print(url_encoded["encoded"])  # SGVsbG8sIHdvcmxkIQ  (no padding, safe chars)

url_decoded = auth.base64_decode(url_encoded["encoded"], url_safe=True)
print(url_decoded["decoded"])  # Hello, world!

Encode a binary blob for JSON transport

from toolkitapi import Auth
import json

auth = Auth(api_key="tk_...")

def encode_binary_for_json(data: bytes) -> str:
    """Encode binary data as URL-safe Base64 for JSON payloads."""
    # Decode bytes to a string (the API accepts strings)
    result = auth.base64_encode(data.decode("latin-1"), url_safe=True)
    return result["encoded"]

Multi-format encode/decode

encode handles formats beyond Base64 — useful for URL encoding, HTML entity escaping, hex encoding, and ascii85 (PDF/PostScript).

from toolkitapi import Auth

auth = Auth(api_key="tk_...")

# URL encode
url = auth.encode("https://toolkitapi.io/search?q=hello world&sort=asc", encoding="url")
print(url["result"])
# https%3A%2F%2Ftoolkitapi.io%2Fsearch%3Fq%3Dhello+world%26sort%3Dasc

# HTML entity encode — sanitise user input for HTML output contexts
html = auth.encode('<script>alert("xss")</script>', encoding="html_entities")
print(html["result"])
# &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;

# Hex encode — inspect binary data, generate colour codes, etc.
hex_enc = auth.encode("Hello", encoding="hex")
print(hex_enc["result"])
# 48656c6c6f

# Decode any of the above — set decode=True
decoded = auth.encode(hex_enc["result"], encoding="hex", decode=True)
print(decoded["result"])  # Hello

Score a form submission for spam

spam_score applies heuristic rules to a form submission and returns a score between 0 (clean) and 1 (spam). It checks for spam phrases, excessive URLs, honeypot fields, fill time, suspicious emails, and more.

from toolkitapi import Auth

auth = Auth(api_key="tk_...")

def check_contact_form(form_data: dict, elapsed_seconds: float) -> dict:
    """Score a contact form submission. Returns score and verdict."""
    result = auth.spam_score(
        body=form_data.get("message", ""),
        name=form_data.get("name"),
        email=form_data.get("email"),
        subject=form_data.get("subject"),
        honeypot=form_data.get("website"),   # hidden field bots fill in
        elapsed_seconds=elapsed_seconds,     # time from page load to submit
    )
    return {
        "score": result["score"],        # 0.0 – 1.0
        "verdict": result["verdict"],    # "clean", "likely_spam", or "spam"
        "signals": result["signals"],    # list of triggered rules
    }

Block high-scoring submissions and log borderline ones

from toolkitapi import Auth

auth = Auth(api_key="tk_...")

SPAM_THRESHOLD = 0.7      # Block above this
REVIEW_THRESHOLD = 0.4    # Flag for review between these two values

def handle_form_submission(form: dict, elapsed: float) -> str:
    result = auth.spam_score(
        body=form.get("message", ""),
        name=form.get("name"),
        email=form.get("email"),
        subject=form.get("subject"),
        honeypot=form.get("hp"),
        elapsed_seconds=elapsed,
    )
    score = result["score"]
    signals = [s["rule"] for s in result["signals"]]

    if score >= SPAM_THRESHOLD:
        # Silently discard — do not tell the sender it was blocked
        return "accepted"

    if score >= REVIEW_THRESHOLD:
        # Save to a moderation queue
        print(f"Flagged for review (score={score:.2f}) — signals: {signals}")
        # ... save to DB ...

    return "accepted"

Response Fields

hash response:

Field Type Description
hash string Hex-encoded hash digest
algorithm string Algorithm used
input_length int Length of the input string in bytes

hmac response:

Field Type Description
hmac string Hex-encoded HMAC digest
algorithm string Algorithm used: sha256, sha384, or sha512

hmac-verify response:

Field Type Description
valid bool Whether the signature matches (constant-time comparison)

base64-encode / base64-decode response:

Field Type Description
encoded / decoded string The encoded or decoded string
encoding string base64 or base64url

encode response:

Field Type Description
result string The encoded or decoded output
encoding string The encoding format used

spam-score response:

Field Type Description
score float Spam probability 0.0 (clean) – 1.0 (spam)
verdict string "clean", "likely_spam", or "spam"
signals list Triggered rules — each has rule, description, weight
total_weight float Raw sum of all triggered rule weights before sigmoid normalisation

Tip

For webhook verification, always use hmac_verify rather than computing the HMAC yourself and comparing with ==. The constant-time comparison prevents timing attacks — a character-by-character == comparison leaks information about how many bytes matched, which an attacker can exploit to forge a valid signature byte by byte.