> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blindfold.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Encryption

> Encrypt sensitive data using AES encryption

## What is Encryption?

Encryption is a reversible privacy protection method that transforms sensitive data into encrypted ciphertext using AES (Advanced Encryption Standard). The data can be decrypted later using the same encryption key.

**Example:**

```
Input:  "API Key: sk-1234567890abcdef"
Output: "API Key: gAAAAABh3K7x9p2Q..."

# With key, can decrypt back to original
Decrypt: "API Key: sk-1234567890abcdef"
```

## How It Works

1. **Detection**: Blindfold identifies sensitive entities in your text
2. **Encryption**: Each entity is encrypted using AES-256 encryption
3. **Key-Based**: Encryption uses your provided key or tenant-specific default
4. **Reversible**: Data can be decrypted using the same key

## When to Use Encryption

Encryption is ideal when you need to:

### 1. Secure Storage of Sensitive Configuration

Encrypt API keys, tokens, and secrets before storing in databases.

```python theme={null}
# Encrypt before storing
config = "Database password: my_secret_pass123"

encrypted = client.encrypt(
    config,
    encryption_key="your-secure-key-min-16-chars"
)

# Store encrypted version
database.save('config', encrypted.text)

# Later, decrypt when needed
# (Note: decrypt endpoint needs to be implemented)
```

**Why this matters:**

* Secrets protected at rest
* Can be decrypted when needed
* Centralized key management

### 2. Protect Data in Transit

Encrypt sensitive data before sending through untrusted channels.

```python theme={null}
# Encrypt before sending
message = "Credit card: 4532-7562-9102-3456"

encrypted = client.encrypt(message, encryption_key=SHARED_KEY)

# Send encrypted version
send_to_partner(encrypted.text)

# Partner decrypts with same key
```

### 3. Temporary Data Protection

Protect data temporarily while it's being processed.

```python theme={null}
# Encrypt user data during processing
user_data = client.encrypt(
    sensitive_user_info,
    encryption_key=SESSION_KEY
)

# Process encrypted data
process_queue.add(user_data.text)

# Decrypt when ready to use
```

### 4. Compliance Requirements

Meet encryption requirements for regulatory compliance (HIPAA, PCI-DSS, etc.).

```python theme={null}
# Encrypt medical records
patient_record = "Patient SSN: 123-45-6789, Diagnosis: ..."

encrypted = client.encrypt(
    patient_record,
    encryption_key=HIPAA_KEY
)

# Store in HIPAA-compliant manner
secure_db.save(encrypted.text)
```

## When NOT to Use Encryption

Encryption is **not suitable** when:

### 1. You Don't Need Reversibility

If you never need the original data, use **Redaction** or **Hashing**.

```python theme={null}
# Bad - unnecessary encryption
encrypted = client.encrypt("Log entry with john@example.com")
# Never decrypted

# Good - use redaction
redacted = client.redact("Log entry with john@example.com")
```

### 2. Users Need to See Partial Data

For UI display, use **Masking** instead.

```python theme={null}
# Bad - user can't see anything useful
encrypted = client.encrypt("Card: 4532-7562-9102-3456")
# Output: "Card: gAAAAABh..."

# Good - show last 4 digits
masked = client.mask("Card: 4532-7562-9102-3456")
# Output: "Card: ***************3456"
```

### 3. Key Management is Too Complex

If managing encryption keys is challenging, use **Tokenization**.

```python theme={null}
# Complex - need to manage encryption keys
encrypted = client.encrypt(data, encryption_key=KEY)
# Must securely store KEY and manage rotation

# Simpler - Blindfold manages tokens
protected = client.tokenize(data)
# Just store the mapping securely
```

## Key Features

<CardGroup cols={2}>
  <Card title="Reversible" icon="arrows-rotate">
    Decrypt data using the encryption key
  </Card>

  <Card title="AES-256" icon="shield">
    Industry-standard encryption algorithm
  </Card>

  <Card title="Custom Keys" icon="key">
    Use your own encryption keys
  </Card>

  <Card title="Secure" icon="lock">
    Strong encryption for sensitive data
  </Card>
</CardGroup>

## Quick Start

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from blindfold import Blindfold
    import os

    client = Blindfold(api_key="your-api-key")

    # Define encryption key (min 16 characters)
    ENCRYPTION_KEY = os.environ["ENCRYPTION_KEY"]

    # Encrypt sensitive data
    result = client.encrypt(
        text="API Key: sk-1234567890abcdef, Secret: my_secret",
        encryption_key=ENCRYPTION_KEY
    )

    print(result.text)
    # "API Key: gAAAAABh..., Secret: gAAAAABh..."

    print(f"Encrypted {result.entities_count} entities")
    # "Encrypted 2 entities"

    # Check what was encrypted
    for entity in result.detected_entities:
        print(f"- {entity.type}: {entity.text}")
    # - API_KEY: sk-1234567890abcdef
    # - PASSWORD: my_secret

    # To decrypt, use the same key with decrypt endpoint
    # (Note: decrypt endpoint needs to be implemented)
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Blindfold } from '@blindfold/sdk';

    const client = new Blindfold({ apiKey: 'your-api-key' });

    // Define encryption key (min 16 characters)
    const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY;

    // Encrypt sensitive data
    const result = await client.encrypt(
      "API Key: sk-1234567890abcdef, Secret: my_secret",
      { encryption_key: ENCRYPTION_KEY }
    );

    console.log(result.text);
    // "API Key: gAAAAABh..., Secret: gAAAAABh..."

    console.log(`Encrypted ${result.entities_count} entities`);
    // "Encrypted 2 entities"

    // Check what was encrypted
    result.detected_entities.forEach(entity => {
      console.log(`- ${entity.type}: ${entity.text}`);
    });
    // - API_KEY: sk-1234567890abcdef
    // - PASSWORD: my_secret

    // To decrypt, use the same key with decrypt endpoint
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    import dev.blindfold.sdk.Blindfold;

    Blindfold client = new Blindfold("your-api-key");

    // Define encryption key (min 16 characters)
    String encryptionKey = System.getenv("ENCRYPTION_KEY");

    // Encrypt sensitive data
    var result = client.encrypt(
        "API Key: sk-1234567890abcdef, Secret: my_secret",
        encryptionKey
    );

    System.out.println(result.getText());
    // "API Key: gAAAAABh..., Secret: gAAAAABh..."

    System.out.println("Encrypted " + result.getEntitiesCount() + " entities");
    // "Encrypted 2 entities"

    // Check what was encrypted
    for (var entity : result.getDetectedEntities()) {
        System.out.println("- " + entity.getType() + ": " + entity.getText());
    }
    // - API_KEY: sk-1234567890abcdef
    // - PASSWORD: my_secret
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST https://api.blindfold.dev/api/public/v1/encrypt \
      -H "X-API-Key: your-api-key" \
      -H "Content-Type: application/json" \
      -d '{
        "text": "API Key: sk-1234567890abcdef, Secret: my_secret",
        "encryption_key": "your-secure-key-min-16-chars"
      }'

    # Response
    {
      "text": "API Key: gAAAAABh3K7x..., Secret: gAAAAABh3K8y...",
      "entities_count": 2,
      "detected_entities": [
        {
          "type": "API_KEY",
          "text": "sk-1234567890abcdef",
          "score": 0.85
        },
        {
          "type": "PASSWORD",
          "text": "my_secret",
          "score": 0.75
        }
      ]
    }
    ```
  </Tab>
</Tabs>

## Configuration Options

### Encryption Key

Provide your own encryption key (minimum 16 characters):

```python theme={null}
# Custom encryption key
ENCRYPTION_KEY = "my-very-secure-encryption-key-123"

result = client.encrypt(
    text=sensitive_data,
    encryption_key=ENCRYPTION_KEY
)

# Default tenant key (if not provided)
result = client.encrypt(text=sensitive_data)
# Uses default key based on tenant ID
```

<Warning>
  **Key Requirements:**

  * Minimum 16 characters
  * Store securely (environment variables, key vault)
  * Use different keys for different environments (dev, prod)
  * Implement key rotation policy
</Warning>

### Filter Entity Types

Only encrypt specific types of data:

```python theme={null}
# Only encrypt API keys and passwords
result = client.encrypt(
    "API Key: sk-123, Email: john@example.com, Password: secret",
    encryption_key=KEY,
    entities=["API_KEY", "PASSWORD"]
)
# Email is NOT encrypted
```

### Adjust Confidence Threshold

Control detection sensitivity:

```python theme={null}
# Only high-confidence encryption
result = client.encrypt(
    text="Maybe secret: xyz123",
    encryption_key=KEY,
    score_threshold=0.8
)
```

## Encryption Algorithm

Blindfold uses **AES-256** encryption with the following process:

1. **Key Derivation**: Your encryption key is derived using PBKDF2
2. **Encryption**: Data is encrypted using Fernet (symmetric encryption)
3. **Secure**: Industry-standard cryptography from `cryptography` library

**Technical Details:**

* Algorithm: AES-256 in CBC mode
* Key derivation: PBKDF2-HMAC-SHA256
* Iterations: 100,000
* Output: Base64-encoded ciphertext

## Common Patterns

### Encrypt Configuration Secrets

```python theme={null}
def store_config(config_data: dict):
    """Encrypt and store configuration"""

    # Serialize config
    config_text = json.dumps(config_data)

    # Encrypt sensitive values
    encrypted = client.encrypt(
        config_text,
        encryption_key=CONFIG_KEY
    )

    # Store encrypted config
    config_db.save('app_config', encrypted.text)

# Usage
config = {
    'database_url': 'postgresql://user:pass@host/db',
    'api_key': 'sk-1234567890',
    'secret_token': 'abc123xyz'
}

store_config(config)
```

### Secure Message Queue

```python theme={null}
def queue_sensitive_message(message: str):
    """Encrypt message before queueing"""

    encrypted = client.encrypt(
        message,
        encryption_key=QUEUE_KEY
    )

    # Queue encrypted message
    message_queue.push(encrypted.text)

# Worker decrypts when processing
def process_message(encrypted_message):
    # Decrypt using same key
    decrypted = decrypt(encrypted_message, QUEUE_KEY)
    process(decrypted)
```

### Temporary Storage

```python theme={null}
def cache_sensitive_data(user_id: str, data: str):
    """Cache encrypted data temporarily"""

    encrypted = client.encrypt(
        data,
        encryption_key=CACHE_KEY
    )

    # Cache with TTL
    redis.setex(
        f"user:{user_id}:data",
        300,  # 5 minutes
        encrypted.text
    )

# Retrieve and decrypt
def get_cached_data(user_id: str):
    encrypted = redis.get(f"user:{user_id}:data")
    if encrypted:
        return decrypt(encrypted, CACHE_KEY)
    return None
```

## Common Use Cases

<AccordionGroup>
  <Accordion title="Secrets Management" icon="vault">
    Encrypt secrets before storing in databases:

    ```python theme={null}
    # Store encrypted secrets
    def save_secret(name: str, value: str):
        encrypted = client.encrypt(
            value,
            encryption_key=SECRETS_KEY
        )

        secrets_db.insert({
            'name': name,
            'value': encrypted.text,
            'encrypted': True
        })

    save_secret('database_password', 'my_db_pass')
    save_secret('api_token', 'token_12345')
    ```

    **Benefits**: Secrets encrypted at rest, can be decrypted when needed
  </Accordion>

  <Accordion title="Secure Data Exchange" icon="right-left">
    Exchange data securely with partners:

    ```python theme={null}
    # Encrypt before sending
    def send_secure_data(data, recipient):
        encrypted = client.encrypt(
            data,
            encryption_key=SHARED_KEYS[recipient]
        )

        api.send_to(recipient, encrypted.text)

    send_secure_data("Sensitive customer data", "partner_a")
    ```

    **Benefits**: Data protected in transit, only recipient can decrypt
  </Accordion>

  <Accordion title="Backup Encryption" icon="floppy-disk">
    Encrypt backups before storage:

    ```python theme={null}
    # Encrypt backup data
    def create_encrypted_backup():
        backup_data = generate_backup()

        encrypted = client.encrypt(
            backup_data,
            encryption_key=BACKUP_KEY
        )

        # Store encrypted backup
        backup_storage.save(encrypted.text)

    create_encrypted_backup()
    ```

    **Benefits**: Backups protected, can restore when needed
  </Accordion>

  <Accordion title="HIPAA Compliance" icon="hospital">
    Encrypt medical records for compliance:

    ```python theme={null}
    # Encrypt patient data
    def store_patient_record(record):
        encrypted = client.encrypt(
            record,
            encryption_key=HIPAA_KEY
        )

        hipaa_db.insert({
            'data': encrypted.text,
            'encrypted_at': datetime.now()
        })

    patient = "Patient: John Doe, SSN: 123-45-6789, Diagnosis: ..."
    store_patient_record(patient)
    ```

    **Benefits**: HIPAA encryption requirements met
  </Accordion>
</AccordionGroup>

## Best Practices

### 1. Secure Key Management

Store encryption keys securely:

```python theme={null}
# Good - use environment variables
ENCRYPTION_KEY = os.environ['ENCRYPTION_KEY']

# Good - use key management service
from cloud_kms import get_key
ENCRYPTION_KEY = get_key('encryption-key-prod')

# Bad - hardcoded in code
ENCRYPTION_KEY = "my-key-123"  # Never do this!
```

### 2. Different Keys for Different Purposes

Use separate keys for different use cases:

```python theme={null}
CONFIG_KEY = os.environ['CONFIG_ENCRYPTION_KEY']
DATA_KEY = os.environ['DATA_ENCRYPTION_KEY']
BACKUP_KEY = os.environ['BACKUP_ENCRYPTION_KEY']

# Encrypt config with config key
encrypted_config = client.encrypt(config, encryption_key=CONFIG_KEY)

# Encrypt data with data key
encrypted_data = client.encrypt(data, encryption_key=DATA_KEY)
```

### 3. Implement Key Rotation

Regularly rotate encryption keys:

```python theme={null}
def rotate_encryption_key():
    """Rotate encryption key for all encrypted data"""

    OLD_KEY = os.environ['OLD_ENCRYPTION_KEY']
    NEW_KEY = os.environ['NEW_ENCRYPTION_KEY']

    # Decrypt with old key, encrypt with new key
    for record in encrypted_records:
        decrypted = decrypt(record.data, OLD_KEY)
        re_encrypted = client.encrypt(decrypted, encryption_key=NEW_KEY)
        update_record(record.id, re_encrypted.text)
```

### 4. Document Encryption Usage

Track what's encrypted and with which key:

```python theme={null}
encrypted_data = {
    'data': encrypted.text,
    'encrypted': True,
    'key_version': 'v2',  # Track key version
    'encrypted_at': datetime.now(),
    'algorithm': 'AES-256'
}
```

## Security Considerations

<Warning>
  Important encryption considerations:

  * **Key security**: Encryption is only as secure as key management
  * **Key loss**: Lost keys mean permanently lost data
  * **Key exposure**: Exposed keys compromise all encrypted data
  * **Algorithm**: Uses AES-256, industry-standard encryption
  * **Not obfuscation**: Encryption is cryptographic protection, not hiding
  * **Compliance**: Check if AES-256 meets your compliance requirements
</Warning>

## Learn More

<CardGroup cols={2}>
  <Card title="Python SDK" icon="python" href="/sdks/python-sdk">
    Full Python SDK documentation
  </Card>

  <Card title="JavaScript SDK" icon="js" href="/sdks/javascript-sdk">
    Complete JavaScript guide
  </Card>

  <Card title="Java SDK" icon="java" href="/sdks/java-sdk">
    Sync and async Java client
  </Card>

  <Card title="REST API" icon="terminal" href="/api-reference/rest-api">
    HTTP API reference for /encrypt
  </Card>

  <Card title="Examples" icon="code" href="/examples">
    Practical integration examples
  </Card>
</CardGroup>

## Compare with Other Methods

<CardGroup cols={2}>
  <Card title="Tokenization" icon="shuffle" href="/methods/tokenization">
    Reversible with mapping (simpler key management)
  </Card>

  <Card title="Masking" icon="eye-slash" href="/methods/masking">
    Partial visibility (no encryption)
  </Card>

  <Card title="Redaction" icon="eraser" href="/methods/redaction">
    Permanent removal (not reversible)
  </Card>

  <Card title="Hashing" icon="hashtag" href="/methods/hashing">
    One-way transformation (not reversible)
  </Card>
</CardGroup>
