# Encryption and Security Examples

Data encryption at rest, in transit, and key management patterns.

## At-Rest Encryption

Encrypt data stored on disk:

```nickel
{
  encryption = {
    at_rest = {
      enabled = true,
      algorithm = "aes-256-gcm",
      key_rotation_days = 90,

      # Storage encryption
      storage = {
        enabled = true,
        type = "block_storage",
        algorithm = "aes-256-gcm",
        key_management = "aws-kms"
      },

      # Database encryption
      database = {
        enabled = true,
        engine = "postgres",
        kms_key_id = "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"
      },

      # Cache encryption
      cache = {
        enabled = true,
        engine = "redis",
        at_rest_encryption = true
      },

      # S3 bucket encryption
      object_storage = {
        enabled = true,
        bucket_encryption = {
          rules = [
            {
              apply_server_side_encryption_by_default = {
                sse_algorithm = "aws:kms",
                kms_master_key_id = "arn:aws:kms:us-east-1:123456789012:key/..."
              }
            }
          ]
        }
      }
    }
  }
}
```

## In-Transit Encryption

TLS/mTLS for all network communication:

```nickel
{
  encryption = {
    in_transit = {
      enabled = true,
      tls_version_min = "1.3",

      # Service-to-service mTLS
      mtls = {
        enabled = true,
        certificate_provider = "cert-manager",
        ca_issuer = "letsencrypt-prod",

        policies = [
          {
            namespace = "production",
            enforce = true,
            mode = "STRICT"
          }
        ]
      },

      # Certificate management
      certificates = {
        issuer = "cert-manager",
        duration = "2160h",  # 90 days
        renewal_threshold = "720h"  # 30 days before expiry
      },

      # Load balancer TLS
      load_balancer = {
        tls_policy = "TLSv1.3",
        ciphers = [
          "TLS_AES_256_GCM_SHA384",
          "TLS_CHACHA20_POLY1305_SHA256",
          "TLS_AES_128_GCM_SHA256"
        ]
      }
    }
  }
}
```

## Post-Quantum Cryptography

Quantum-resistant encryption with SecretumVault:

```nushell
#!/usr/bin/env nu

# Initialize SecretumVault with PQC
plugin add nu_plugin_secretumvault

# Configure post-quantum cryptography
export SECRETUMVAULT_CIPHER=kyber-aes  # PQC + classical hybrid
export SECRETUMVAULT_KDF=argon2id      # Memory-hard KDF

# Initialize vault
secretumvault-plugin init

# Store secrets with PQC encryption
def store_secret_pqc [name value] {
  # Encrypts with CRYSTALS-Kyber + AES-256-GCM hybrid
  secretumvault-plugin store $name $value
}

# Retrieve and decrypt
def retrieve_secret_pqc [name] {
  secretumvault-plugin retrieve $name
}

# Example usage
store_secret_pqc "database-password" "SecurePassword123!"
let db_pass = retrieve_secret_pqc "database-password"

print "Stored and retrieved secret using post-quantum cryptography"
```

## Key Rotation

Automatic key rotation strategy:

```nickel
{
  key_management = {
    rotation = {
      enabled = true,
      rotation_period_days = 90,
      rotation_window = "02:00-04:00",

      # Automated rotation for database encryption
      database_keys = {
        enabled = true,
        rotation_period = 90,
        automatic = true,
        test_before_rotation = true
      },

      # Application secret rotation
      application_secrets = {
        enabled = true,
        rotation_period = 30,
        gradual_rollout = true,
        parallel_versions = 2  # Keep 2 versions during rollover
      },

      # TLS certificate rotation
      tls_certificates = {
        enabled = true,
        auto_renewal_enabled = true,
        renewal_threshold_days = 30
      },

      # AWS KMS key rotation
      kms_keys = {
        enabled = true,
        auto_rotation = true
      }
    },

    # Key versioning
    versioning = {
      enabled = true,
      retention_period_days = 365,
      archive_old_keys = true
    },

    # Key backup and recovery
    backup = {
      enabled = true,
      backup_frequency = "daily",
      replicate_to_region = "us-west-2"
    }
  }
}
```

## Secrets Management

Secure credential storage and injection:

```nushell
#!/usr/bin/env nu

# Load SecretumVault plugin
plugin add nu_plugin_secretumvault

# Define secrets structure
let secrets = {
  database = {
    username = "admin",
    password = "SecurePassword123!"
  },
  api = {
    key = "sk-abc123def456",
    secret = "secret-key-value"
  },
  certificates = {
    tls_cert = (open certs/server.crt | into string),
    tls_key = (open certs/server.key | into string)
  }
}

# Store secrets (encrypted)
def setup_secrets [] {
  # Store database credentials
  secretumvault-plugin store "db.username" $secrets.database.username
  secretumvault-plugin store "db.password" $secrets.database.password

  # Store API keys
  secretumvault-plugin store "api.key" $secrets.api.key
  secretumvault-plugin store "api.secret" $secrets.api.secret

  # Store certificates
  secretumvault-plugin store "tls.cert" $secrets.certificates.tls_cert
  secretumvault-plugin store "tls.key" $secrets.certificates.tls_key

  print "Secrets stored securely"
}

# Inject secrets into environment for application
def inject_secrets_into_application [] {
  let db_user = secretumvault-plugin retrieve "db.username"
  let db_pass = secretumvault-plugin retrieve "db.password"
  let api_key = secretumvault-plugin retrieve "api.key"

  # Create environment
  with-env {
    DATABASE_USER: $db_user,
    DATABASE_PASSWORD: $db_pass,
    API_KEY: $api_key,
    API_SECRET: (secretumvault-plugin retrieve "api.secret")
  } {
    # Run application
    ./application.sh
  }
}

# Secret rotation
def rotate_secret [secret_name new_value] {
  # Store new version
  secretumvault-plugin store $secret_name $new_value

  # Mark old version for retirement
  print $"Rotated secret: ($secret_name)"
}

# Setup and run
setup_secrets
inject_secrets_into_application
```

## Certificate Management

TLS certificate lifecycle:

```nushell
#!/usr/bin/env nu

# Certificate generation and management
def generate-certificate [domain] {
  print $"Generating certificate for ($domain)..."

  # Generate private key
  exec openssl genrsa -out $"($domain).key" 2048

  # Generate certificate request
  exec openssl req -new \
    -key $"($domain).key" \
    -out $"($domain).csr" \
    -subj "/CN=$domain"

  # Sign with CA (or request from ACME)
  exec openssl x509 -req \
    -in $"($domain).csr" \
    -CA ca.crt \
    -CAkey ca.key \
    -CAcreateserial \
    -out $"($domain).crt" \
    -days 365

  print "Certificate generated"
}

# Certificate verification
def verify-certificate [cert_path] {
  print $"Verifying certificate: ($cert_path)"

  let cert_info = (exec openssl x509 -in $cert_path -text -noout)
  let expiry_date = ($cert_info | grep "Not After" | str trim)

  print $cert_info
  print $"Expiry: ($expiry_date)"
}

# Certificate renewal (before expiry)
def renew-certificate [domain] {
  print $"Renewing certificate for ($domain)"

  # Check expiry
  let days_until_expiry = (
    exec openssl x509 -in $"($domain).crt" -noout -dates |
    grep "notAfter" |
    str replace "notAfter=" "" |
    date parse "%b %d %T %Y %Z" |
    date subtract (now) |
    math floor
  )

  if $days_until_expiry < 30 {
    generate-certificate $domain
    print "Certificate renewed"
  } else {
    print $"Certificate valid for ($days_until_expiry) more days"
  }
}

# Install certificate in load balancer
def install-certificate-in-lb [domain cert_path key_path] {
  print $"Installing certificate for ($domain) in load balancer"

  let cert_data = open $cert_path | into string
  let key_data = open $key_path | into string

  http post " [http://load-balancer-api/certificates"](http://load-balancer-api/certificates") \
    --data {
      domain: $domain,
      certificate: $cert_data,
      private_key: $key_data,
      enabled: true
    }

  print "Certificate installed"
}
```

## Encrypted Configuration

Encrypt sensitive configuration values:

```nushell
#!/usr/bin/env nu

plugin add nu_plugin_kms

# Load Nickel configuration
let config = open infrastructure.ncl | nickel eval

# Encrypt sensitive fields
def encrypt-sensitive-config [config] {
  let encrypted = {
    database = {
      ...$config.database,
      password: ($config.database.password | kms encrypt --algorithm aes-256-gcm)
    },
    api = {
      ...$config.api,
      secret: ($config.api.secret | kms encrypt --algorithm aes-256-gcm)
    }
  }

  $encrypted
}

# Decrypt for use
def decrypt-sensitive-config [config] {
  let decrypted = {
    database = {
      ...$config.database,
      password: ($config.database.password | kms decrypt)
    },
    api = {
      ...$config.api,
      secret: ($config.api.secret | kms decrypt)
    }
  }

  $decrypted
}

# Save encrypted configuration
let encrypted_config = encrypt-sensitive-config $config
$encrypted_config | to json | save infrastructure.encrypted.json

# Load and decrypt when needed
let saved_config = open infrastructure.encrypted.json | from json
let working_config = decrypt-sensitive-config $saved_config
```

## Network Encryption

VPN and network-level encryption:

```nickel
{
  network = {
    # VPN for infrastructure access
    vpn = {
      enabled = true,
      protocol = "wireguard",
      endpoint = "vpn.prod.internal",
      port = 51820,

      # Client configurations
      clients = [
        {
          name = "developer-01",
          public_key = "...",
          allowed_ips = ["10.0.0.0/8"],
          endpoint = "vpn.example.com"
        },
        {
          name = "ci-runner",
          public_key = "...",
          allowed_ips = ["10.0.0.0/8"]
        }
      ]
    },

    # IPSec tunnel encryption (site-to-site)
    ipsec = {
      enabled = true,
      tunnels = [
        {
          name = "aws-to-upcloud",
          local = { ip = "203.0.113.1", subnet = "10.1.0.0/16" },
          remote = { ip = "198.51.100.1", subnet = "10.2.0.0/16" },
          encryption = {
            algorithm = "aes256",
            authentication = "sha256"
          }
        }
      ]
    },

    # Wireguard mesh network
    mesh = {
      enabled = true,
      name = "infra-mesh",
      peers = [
        { name = "node-1", ip = "10.255.0.1" },
        { name = "node-2", ip = "10.255.0.2" },
        { name = "node-3", ip = "10.255.0.3" }
      ]
    }
  }
}
```

## Related Documentation

- [SecretumVault Guide](../security/secretumvault-guide.md)
- [KMS Guide](../security/kms-guide.md)
- [Security System](../features/security-system.md)
- [Secrets Management](../security/secrets-management.md)
