Skip to main content

darkstrata-credential-check

Check if credentials have been exposed in data breaches using k-anonymity.

PyPI version License

Features

  • Privacy-first: Uses k-anonymity to check credentials without exposing them
  • Type-safe: Full type hints with comprehensive dataclass definitions
  • Async-first: Built on httpx for efficient async HTTP operations
  • Automatic caching: Intelligent caching aligned with server time windows
  • Batch processing: Efficiently check multiple credentials with automatic prefix grouping
  • Retry logic: Built-in exponential backoff for transient failures
  • Comprehensive errors: Detailed error types for easy error handling

Prerequisites

  1. Get an API key from https://darkstrata.io
  2. Python 3.10 or higher

Installation

pip install darkstrata-credential-check
poetry add darkstrata-credential-check
uv add darkstrata-credential-check

Quick Start

import asyncio
from darkstrata_credential_check import DarkStrataCredentialCheck, hash_credential

async def main():
    # Create a client
    async with DarkStrataCredentialCheck(api_key='your-api-key') as client:
        # email and password come from your login form and are only ever used here.
        # 1. Hash the credential locally: SHA-256 of "email:password".
        #    The plaintext email and password never leave this process.
        hash_value = hash_credential(email, password)

        # 2. Check the hash. The SDK sends only the first 5-6 characters (the
        #    k-anonymity prefix) to the API and compares the full hash locally.
        result = await client.check_hash(hash_value)

        if result.found:
            print('WARNING: This credential was found in a data breach!')
        else:
            print('Credential not found in known breaches.')

asyncio.run(main())

How It Works

This SDK uses k-anonymity to check credentials without exposing them:

  1. Your credential is hashed locally: SHA256(email:password)
  2. Only the first 5 or 6 characters (prefix) of the hash are sent to the API
  3. The API returns all hashes matching that prefix (1-in-1,000,000 anonymity)
  4. The SDK checks if your full hash is in the returned set

Your actual credentials never leave your system.

┌─────────────────────┐         ┌─────────────────────┐
│     Your System     │         │   DarkStrata API    │
│                     │         │                     │
│  email:password     │         │                     │
│        ↓            │         │                     │
│  SHA256 hash        │         │                     │
│        ↓            │         │                     │
│  Extract prefix ────┼────────→│  Lookup by prefix   │
│  (5 chars only)     │         │        ↓            │
│                     │←────────┼─ Return all matches │
│  Check membership   │         │                     │
│        ↓            │         │                     │
│  found: true/false  │         │                     │
└─────────────────────┘         └─────────────────────┘

API Reference

DarkStrataCredentialCheck

The main client class.

Constructor

DarkStrataCredentialCheck(
    api_key: str,
    *,
    base_url: str = 'https://api.darkstrata.io/v1/',
    timeout: float = 30.0,
    retries: int = 3,
    enable_caching: bool = True,
    cache_ttl: int = 3600,
)

Parameters:

Parameter Type Default Description
api_key str required Your DarkStrata API key
base_url str 'https://api.darkstrata.io/v1/' API base URL
timeout float 30.0 Request timeout in seconds
retries int 3 Number of retry attempts
enable_caching bool True Enable response caching
cache_ttl int 3600 Cache TTL in seconds (1 hour)

Methods

check(email, password, options?)

Check a single credential.

result = await client.check('user@example.com', 'password123')

Returns: CheckResult

check_hash(hash, options?)

Check a pre-computed SHA-256 hash.

hash_value = '5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8...'
result = await client.check_hash(hash_value)

Returns: CheckResult

check_batch(credentials, options?)

Check multiple credentials efficiently.

from darkstrata_credential_check import Credential

results = await client.check_batch([
    Credential(email='user1@example.com', password='pass1'),
    Credential(email='user2@example.com', password='pass2'),
])

Returns: list[CheckResult]

check_hash_batch(hashes, options?)

Check multiple pre-computed hashes efficiently. Results are in input order with credential.email set to [hash-only].

hashes = [hash_credential(c.email, c.password) for c in credentials]
results = await client.check_hash_batch(hashes)

Returns: list[CheckResult]

clear_cache()

Clear the internal response cache.

client.clear_cache()
get_cache_size()

Get the number of cached entries.

size = client.get_cache_size()

CheckResult

The result of a credential check.

@dataclass
class CheckResult:
    found: bool                    # true if credential was in a breach
    credential: CredentialInfo     # info about the credential checked
    metadata: CheckMetadata        # additional metadata

CheckMetadata

Metadata returned with check results.

@dataclass
class CheckMetadata:
    prefix: str                    # The 5 or 6-char prefix used
    total_results: int             # Total hashes returned by API
    hmac_source: Literal['server', 'client']  # Source of HMAC key
    time_window: int | None        # Server time window (server HMAC only)
    filter_since: int | None       # Epoch day filter (if since was used)
    cached_result: bool            # Whether result was from cache
    checked_at: datetime           # When the check was performed

CheckOptions

Optional parameters for check requests.

@dataclass
class CheckOptions:
    client_hmac: str | None = None   # Your own HMAC key (64+ hex chars)
    since: int | datetime | None = None  # Filter by breach date

Error Handling

The SDK provides specific error types for different failure scenarios:

from darkstrata_credential_check import (
    DarkStrataCredentialCheck,
    AuthenticationError,
    ValidationError,
    ApiError,
    TimeoutError,
    NetworkError,
    RateLimitError,
    is_darkstrata_error,
)

async with DarkStrataCredentialCheck(api_key='your-key') as client:
    try:
        result = await client.check('user@example.com', 'password')
    except AuthenticationError:
        print('Invalid API key')
    except ValidationError as error:
        print(f'Invalid input: {error.field}')
    except RateLimitError as error:
        if error.retry_after:
            print(f'Rate limited. Retry after {error.retry_after} seconds')
    except TimeoutError as error:
        print(f'Request timed out after {error.timeout_seconds}s')
    except NetworkError as error:
        print(f'Network error: {error}')
    except ApiError as error:
        print(f'API error ({error.status_code}): {error}')
    except Exception as error:
        if is_darkstrata_error(error):
            print(f'DarkStrata error [{error.code}]: {error}')
        else:
            raise

Error Types

Error Code Description
AuthenticationError AUTHENTICATION_ERROR Invalid or missing API key
ValidationError VALIDATION_ERROR Invalid input parameters
ApiError API_ERROR API request failed
TimeoutError TIMEOUT_ERROR Request timed out
NetworkError NETWORK_ERROR Network connectivity issue
RateLimitError RATE_LIMIT_ERROR Rate limit exceeded

Advanced Usage

Pre-computed Hashes

If you're storing hashed credentials, you can check them directly:

from darkstrata_credential_check import hash_credential, DarkStrataCredentialCheck

# Compute hash once
hash_value = hash_credential('user@example.com', 'password123')
# Store hash securely...

# Later, check the hash
async with DarkStrataCredentialCheck(api_key='your-key') as client:
    result = await client.check_hash(hash_value)

Batch Processing

For checking multiple credentials, use check_batch for efficiency:

from darkstrata_credential_check import Credential

credentials = [
    Credential(email='user1@example.com', password='pass1'),
    Credential(email='user2@example.com', password='pass2'),
    Credential(email='user3@example.com', password='pass3'),
]

results = await client.check_batch(credentials)

compromised = [r for r in results if r.found]
print(f'{len(compromised)} credentials were compromised')

Batch processing automatically groups credentials by prefix to minimise API calls.

Client-Provided HMAC Key

By default, the server generates a time-rotating HMAC key. For deterministic results across requests, provide your own key:

import secrets
from darkstrata_credential_check import CheckOptions

# Generate a secure key once and store it securely
client_hmac = secrets.token_hex(32)  # 64 hex chars = 256 bits

result = await client.check('user@example.com', 'password',
    CheckOptions(client_hmac=client_hmac))

# Results are now deterministic (not time-windowed)
print(result.metadata.hmac_source)  # 'client'

When to use client HMAC:

  • You need consistent results across multiple requests
  • You're comparing results from different time periods
  • You want to avoid server-side key rotation

Date Filtering

Filter results to only include breaches from a specific date onwards:

from datetime import datetime
from darkstrata_credential_check import CheckOptions

# Only check breaches from 2024 onwards
result = await client.check('user@example.com', 'password',
    CheckOptions(since=datetime(2024, 1, 1)))

# Or use epoch day (days since 1 January 1970)
result = await client.check('user@example.com', 'password',
    CheckOptions(since=19724))  # 2024-01-01

# Check the filter applied
print(result.metadata.filter_since)  # 19724

Combined Options

You can combine multiple options:

result = await client.check('user@example.com', 'password',
    CheckOptions(
        client_hmac='your-256-bit-hex-key...',
        since=datetime(2024, 1, 1),
    ))

Disabling Cache

For real-time checks where you need fresh results:

client = DarkStrataCredentialCheck(
    api_key='your-key',
    enable_caching=False,
)

Custom Timeout and Retries

client = DarkStrataCredentialCheck(
    api_key='your-key',
    timeout=60.0,  # 60 seconds
    retries=5,     # 5 retry attempts
)

Security Considerations

What is sent to the API?

  • Only the first 5 or 6 characters of the SHA-256 hash
  • Your API key for authentication

What is NOT sent?

  • Your email address
  • Your password
  • The full hash of your credentials

Best Practices

  1. Never log credentials - The SDK never logs credentials, and you shouldn't either
  2. Use HTTPS - The SDK enforces HTTPS for all API calls
  3. Secure your API key - Store your API key securely (environment variables, secrets manager)
  4. Handle errors gracefully - Don't expose internal errors to end users

Type Hints

This package includes comprehensive type hints and exports all types:

from darkstrata_credential_check import (
    ClientOptions,
    Credential,
    CheckOptions,
    CheckResult,
    CheckMetadata,
    CredentialInfo,
)

Context Manager

The client supports async context manager for proper resource cleanup:

async with DarkStrataCredentialCheck(api_key='your-key') as client:
    result = await client.check('user@example.com', 'password')
# HTTP client is automatically closed

Alternatively, close manually:

client = DarkStrataCredentialCheck(api_key='your-key')
try:
    result = await client.check('user@example.com', 'password')
finally:
    await client.close()

Contributing

See the contributing guide.

Licence

Apache 2.0 (c) DarkStrata

Metadata

Release files for darkstrata-credential-check 2.4.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for darkstrata-credential-check 2.4.1
File Size Uploaded Provenance Actions
darkstrata_credential_check-2.4.1.tar.gz 29.6 kB With provenance Details for darkstrata_credential_check-2.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for darkstrata-credential-check 2.4.1
File Interpreter ABI Platform Actions
darkstrata_credential_check-2.4.1-py3-none-any.whl Python 3 none any Details for darkstrata_credential_check-2.4.1-py3-none-any.whl

Total release size: 53.5 kB

Release files / darkstrata_credential_check-2.4.1.tar.gz

Download URL darkstrata_credential_check-2.4.1.tar.gz
Size 29.6 kB
Tags Source
SHA-256 checksum
How to use checksums
339e14d57a2581312eae92df423e1fea8b93d505c6617b2d83cee81111d2cfb7
BLAKE2b-256 checksum
How to use checksums
e12ab25adfc8df614d74b253b1ed2d6567c165e9408e1ea14bf76144f035c157
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 13, 2026.

Transparency log

Release files / darkstrata_credential_check-2.4.1-py3-none-any.whl

Download URL darkstrata_credential_check-2.4.1-py3-none-any.whl
Size 23.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
192c45dc5fdf912132cd2a19642ed5c009e82e7920c95f0f98bb57b90bd690ee
BLAKE2b-256 checksum
How to use checksums
952e5606ab606f0d5790a475f9a2342914f2e284bea15e6d18518992c9702e62
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 13, 2026.

Transparency log

Security for darkstrata-credential-check 2.4.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for darkstrata_credential_check-2.4.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page