Skip to main content

Chapter 8: Security Architecture and Encryption

Overview

Vektagraf implements a comprehensive security architecture that provides multiple layers of protection for your data. This chapter covers the encryption systems, key management strategies, and advanced privacy-preserving features that make Vektagraf suitable for handling sensitive data in regulated environments.

Learning Objectives

By the end of this chapter, you will understand:

  • Vektagraf's multi-layered security architecture
  • Encryption at rest and in transit implementation
  • Key management and rotation strategies
  • Homomorphic encryption for privacy-preserving computations
  • Field-level encryption and selective disclosure
  • Best practices for secure deployment

Prerequisites

  • Understanding of basic cryptographic concepts
  • Familiarity with Vektagraf schema design (Chapter 3)
  • Knowledge of database operations (Chapter 4)

Core Security Architecture

Vektagraf's security architecture follows a defense-in-depth approach with multiple layers of protection:

Security Layers

graph TB
    A[Application Layer] --> B[Transport Security]
    B --> C[Authentication & Authorization]
    C --> D[Field-Level Encryption]
    D --> E[Database Encryption]
    E --> F[Storage Encryption]
    F --> G[Hardware Security]
    
    A1[API Security] --> A
    A2[Input Validation] --> A
    
    B1[TLS 1.3] --> B
    B2[Certificate Pinning] --> B
    
    C1[RBAC/ABAC] --> C
    C2[Multi-Factor Auth] --> C
    
    D1[Selective Disclosure] --> D
    D2[Homomorphic Encryption] --> D
    
    E1[AES-256-GCM] --> E
    E2[ChaCha20-Poly1305] --> E
    
    F1[File System Encryption] --> F
    F2[Volume Encryption] --> F

Security Configuration

Configure security settings in your schema:

{
  "security": {
    "encryption": {
      "algorithm": "AES-256-GCM",
      "keyRotationInterval": "monthly",
      "enableHomomorphic": true
    },
    "authentication": {
      "multiFactorRequired": true,
      "sessionTimeout": "8h",
      "maxFailedAttempts": 3
    },
    "audit": {
      "enabled": true,
      "retentionPeriod": "7y",
      "realTimeAlerts": true
    }
  }
}

Encryption at Rest

Vektagraf provides multiple levels of encryption for data at rest, from database-level encryption to field-level granular protection.

Database-Level Encryption

All data stored by Vektagraf is encrypted using industry-standard algorithms:

import 'package:vektagraf/vektagraf.dart';

// Configure database encryption
final config = VektagrafConfig(
  encryptionConfig: EncryptionConfig(
    algorithm: EncryptionAlgorithm.aes256Gcm,
    keyDerivation: KeyDerivationConfig(
      algorithm: 'HKDF-SHA256',
      iterations: 100000,
    ),
    enableCompression: true,
  ),
);

final database = await Vektagraf.open(
  'secure_database',
  config: config,
);

Field-Level Encryption

Encrypt specific fields based on sensitivity:

{
  "models": {
    "User": {
      "fields": {
        "id": {"type": "string", "primary": true},
        "email": {"type": "string", "indexed": true},
        "ssn": {
          "type": "string",
          "encrypted": true,
          "encryptionAlgorithm": "AES-256-GCM"
        },
        "creditCard": {
          "type": "string",
          "encrypted": true,
          "encryptionAlgorithm": "ChaCha20-Poly1305",
          "accessRoles": ["admin", "finance"]
        }
      }
    }
  }
}

Encryption Implementation Example

// Working with encrypted fields
final user = User()
  ..email = 'user@example.com'
  ..ssn = '123-45-6789'  // Automatically encrypted
  ..creditCard = '4111-1111-1111-1111';  // Encrypted with role-based access

await database.users.create(user);

// Reading encrypted data (automatic decryption with proper permissions)
final retrievedUser = await database.users.findById(user.id);
print(retrievedUser.email);  // Plaintext (not encrypted)
print(retrievedUser.ssn);    // Decrypted if user has permission

Encryption in Transit

All network communication is secured using modern cryptographic protocols.

TLS Configuration

final transportConfig = TransportConfig(
  tls: TlsConfig(
    version: TlsVersion.v1_3,
    cipherSuites: [
      'TLS_AES_256_GCM_SHA384',
      'TLS_CHACHA20_POLY1305_SHA256',
    ],
    certificatePinning: true,
    enableOcspStapling: true,
  ),
);

final client = VektagrafClient(
  serverUrl: 'https://secure-server.example.com',
  transportConfig: transportConfig,
);

End-to-End Encryption

For maximum security, implement end-to-end encryption:

// Generate client-side encryption key
final clientKey = EncryptionKey.generate('AES-256-GCM');

// Encrypt sensitive data before sending
final encryptedData = await encryptionEngine.encrypt(
  sensitiveData,
  clientKey,
);

// Store encrypted data
final record = SecureRecord()
  ..encryptedPayload = encryptedData.toBytes()
  ..keyId = clientKey.keyId;

await database.secureRecords.create(record);

Key Management and Rotation

Vektagraf implements a comprehensive key management system with automatic rotation and hierarchical key derivation.

Key Hierarchy

graph TD
    A[Master Key] --> B[Tenant Keys]
    A --> C[Model Keys]
    A --> D[Field Keys]
    
    B --> B1[Tenant A Key]
    B --> B2[Tenant B Key]
    
    C --> C1[User Model Key]
    C --> C2[Order Model Key]
    
    D --> D1[SSN Field Key]
    D --> D2[Credit Card Field Key]
    
    B1 --> E1[Tenant A User Key]
    B1 --> E2[Tenant A Order Key]

Key Management Setup

// Initialize key manager with rotation policy
final keyManager = KeyManager(
  keyStore: FileKeyStore(
    keyStorePath: '/secure/keys',
    storeEncryptionKey: masterKey,
  ),
  rotationPolicy: KeyRotationPolicy.fromString('monthly'),
);

await keyManager.initialize();

// Get field-specific encryption key
final ssnKey = await keyManager.getFieldKey('User', 'ssn');
final creditCardKey = await keyManager.getFieldKey('User', 'creditCard');

Automatic Key Rotation

// Configure automatic key rotation
final rotationScheduler = KeyRotationScheduler(
  keyManager: keyManager,
  schedule: RotationSchedule(
    interval: Duration(days: 30),
    gracePeriod: Duration(days: 7),  // Keep old keys for decryption
  ),
);

// Start automatic rotation
await rotationScheduler.start();

// Manual key rotation
await keyManager.rotateKey('field.User.ssn');

Key Derivation

Vektagraf uses HKDF (HMAC-based Key Derivation Function) for secure key derivation:

// Derive tenant-specific key
final tenantKey = await keyManager.getTenantKey('tenant-123');

// Derive field-specific key with context
final fieldKey = keyDerivation.deriveFieldKey(
  'User', 
  'ssn',
  salt: contextSalt,
  rotationId: 'rotation-456',
);

Homomorphic Encryption

Vektagraf supports homomorphic encryption for privacy-preserving computations on encrypted data.

Paillier Cryptosystem

// Generate Paillier key pair
final paillier = PaillierCryptosystem.generate(
  bitLength: 2048,
  keyId: 'analytics-key',
);

// Encrypt sensitive numeric data
final salary1 = paillier.encrypt(75000.0);
final salary2 = paillier.encrypt(85000.0);

// Perform computations on encrypted data
final totalSalary = salary1 + salary2;  // Homomorphic addition
final avgSalary = totalSalary.multiply(0.5);  // Scalar multiplication

// Decrypt result
final result = paillier.decrypt(avgSalary);
print('Average salary: \$${result.toStringAsFixed(2)}');

Vector Operations

// Encrypt vectors for similarity search
final vector1 = [0.1, 0.2, 0.3, 0.4];
final vector2 = [0.2, 0.1, 0.4, 0.3];

final encryptedVector1 = paillier.encryptVector(vector1);
final encryptedVector2 = paillier.encryptVector(vector2);

// Compute encrypted similarity
final vectorOps = HomomorphicVectorOperations(paillier);
final encryptedSimilarity = await vectorOps.encryptedCosineSimilarity(
  encryptedVector1,
  encryptedVector2,
);

// Decrypt similarity score
final similarity = paillier.decrypt(encryptedSimilarity);

Secure Analytics

// Perform analytics on encrypted data
class SecureAnalytics {
  final PaillierCryptosystem cryptosystem;
  
  SecureAnalytics(this.cryptosystem);
  
  Future<EncryptedValue> computeEncryptedSum(
    List<EncryptedValue> values,
  ) async {
    return values.reduce((a, b) => a + b);
  }
  
  Future<EncryptedValue> computeEncryptedAverage(
    List<EncryptedValue> values,
  ) async {
    final sum = await computeEncryptedSum(values);
    return sum.multiply(1.0 / values.length);
  }
}

// Usage
final analytics = SecureAnalytics(paillier);
final encryptedSalaries = [
  paillier.encrypt(75000.0),
  paillier.encrypt(85000.0),
  paillier.encrypt(95000.0),
];

final encryptedAvg = await analytics.computeEncryptedAverage(encryptedSalaries);
final averageSalary = paillier.decrypt(encryptedAvg);

Field-Level Encryption and Selective Disclosure

Implement granular access control with field-level encryption and selective disclosure.

Selective Disclosure Configuration

{
  "models": {
    "Employee": {
      "fields": {
        "id": {"type": "string", "primary": true},
        "name": {"type": "string"},
        "salary": {
          "type": "number",
          "selectiveDisclosure": {
            "alwaysDisclose": false,
            "requiredRoles": ["hr", "manager"],
            "allowedPurposes": ["payroll", "audit"]
          }
        },
        "ssn": {
          "type": "string",
          "selectiveDisclosure": {
            "neverDisclose": true,
            "requiredRoles": ["admin"],
            "constraints": {
              "purpose": "legal_compliance"
            }
          }
        }
      }
    }
  }
}

Selective Disclosure Implementation

// Create selective disclosure manager
final disclosureManager = SelectiveDisclosureManager(
  securityEngine: securityPolicyEngine,
  auditLogger: auditLogger,
);

// Generate selective disclosure token
final employee = await database.employees.findById('emp-123');
final token = await disclosureManager.generateToken(
  context: securityContext,
  modelName: 'Employee',
  object: employee.toJson(),
  disclosureFields: ['name', 'department'],  // Only disclose these fields
  purpose: 'background_check',
  validity: Duration(hours: 24),
);

// Verify and use token
final isValid = await disclosureManager.verifyToken(
  token: token,
  verifierId: 'verifier-456',
);

if (isValid) {
  final disclosedData = token.disclosedClaims;
  print('Name: ${disclosedData['name']}');
  // Salary and SSN are committed but not disclosed
}

Zero-Knowledge Proofs

// Create zero-knowledge proof for age verification
final ageProof = ZeroKnowledgeProof(
  fieldName: 'age',
  proofType: 'range',
  proof: generateRangeProof(actualAge, minAge: 18, maxAge: 120),
  publicParameters: {
    'min': 18,
    'max': 120,
    'statement': 'Age is between 18 and 120',
  },
);

// Verify proof without revealing actual age
final isValidAge = ageProof.verify();
print('Age verification: ${isValidAge ? 'PASS' : 'FAIL'}');

Advanced Security Features

Secure Multi-Party Computation

// Implement secure computation protocols
class SecureComputationProtocol {
  Future<EncryptedValue> secureMultiplication(
    EncryptedValue a,
    EncryptedValue b,
  ) async {
    // Use secure multiplication protocol
    final secureMultiplier = SecureMultiplication(cryptosystem);
    return await secureMultiplier.multiply(a, b);
  }
  
  Future<EncryptedValue> secureDivision(
    EncryptedValue dividend,
    EncryptedValue divisor,
  ) async {
    // Use secure division protocol
    final secureDivider = SecureDivision(cryptosystem);
    return await secureDivider.divide(dividend, divisor);
  }
}

Differential Privacy

// Add noise for differential privacy
class DifferentialPrivacy {
  final double epsilon;  // Privacy budget
  
  DifferentialPrivacy({this.epsilon = 1.0});
  
  double addLaplaceNoise(double value) {
    final random = Random.secure();
    final u = random.nextDouble() - 0.5;
    final noise = -1 / epsilon * (u >= 0 ? 1 : -1) * log(1 - 2 * u.abs());
    return value + noise;
  }
  
  List<double> addGaussianNoise(List<double> values, double sensitivity) {
    final sigma = sensitivity * sqrt(2 * log(1.25)) / epsilon;
    final random = Random.secure();
    
    return values.map((value) {
      final noise = _generateGaussianNoise(random) * sigma;
      return value + noise;
    }).toList();
  }
  
  double _generateGaussianNoise(Random random) {
    // Box-Muller transform for Gaussian noise
    final u1 = random.nextDouble();
    final u2 = random.nextDouble();
    return sqrt(-2 * log(u1)) * cos(2 * pi * u2);
  }
}

Security Best Practices

Secure Configuration

// Production security configuration
final secureConfig = VektagrafConfig(
  security: SecurityConfig(
    encryption: EncryptionConfig(
      algorithm: EncryptionAlgorithm.aes256Gcm,
      keySize: 256,
      enableHardwareAcceleration: true,
    ),
    authentication: AuthenticationConfig(
      multiFactorRequired: true,
      passwordPolicy: PasswordPolicy(
        minLength: 12,
        requireSpecialChars: true,
        requireNumbers: true,
        requireUppercase: true,
        maxAge: Duration(days: 90),
      ),
      sessionConfig: SessionConfig(
        timeout: Duration(hours: 8),
        renewalThreshold: Duration(minutes: 30),
        maxConcurrentSessions: 3,
      ),
    ),
    audit: AuditConfig(
      enabled: true,
      logLevel: AuditLogLevel.detailed,
      retentionPeriod: Duration(days: 2555),  // 7 years
      encryptLogs: true,
      realTimeAlerts: true,
    ),
  ),
);

Key Storage Security

// Secure key storage with HSM integration
final hsmKeyStore = HsmKeyStore(
  hsmConfig: HsmConfig(
    provider: 'PKCS11',
    libraryPath: '/usr/lib/libpkcs11.so',
    slotId: 0,
    pin: securePin,
  ),
);

// Use hardware security module for key operations
final keyManager = KeyManager(
  keyStore: hsmKeyStore,
  rotationPolicy: KeyRotationPolicy(
    rotationInterval: Duration(days: 30),
    autoRotate: true,
    retainOldKeys: 3,
  ),
);

Network Security

// Configure secure transport
final transportSecurity = TransportSecurity(
  tls: TlsConfig(
    version: TlsVersion.v1_3,
    mutualAuthentication: true,
    certificateValidation: CertificateValidation.strict,
    ocspStapling: true,
  ),
  networkSecurity: NetworkSecurityConfig(
    allowedCipherSuites: [
      'TLS_AES_256_GCM_SHA384',
      'TLS_CHACHA20_POLY1305_SHA256',
    ],
    minimumKeySize: 2048,
    enablePerfectForwardSecrecy: true,
  ),
);

Performance Considerations

Encryption Performance Optimization

// Optimize encryption performance
class EncryptionOptimizer {
  final Map<String, EncryptionEngine> _engineCache = {};
  
  EncryptionEngine getOptimizedEngine(String algorithm) {
    return _engineCache.putIfAbsent(algorithm, () {
      final engine = EncryptionEngineFactory.create(algorithm);
      
      // Enable hardware acceleration if available
      if (engine.supportsHardwareAcceleration) {
        engine.enableHardwareAcceleration();
      }
      
      return engine;
    });
  }
  
  Future<List<EncryptionResult>> batchEncrypt(
    List<Uint8List> plaintexts,
    EncryptionKey key,
  ) async {
    final engine = getOptimizedEngine(key.algorithm);
    
    // Use parallel processing for batch operations
    final futures = plaintexts.map((plaintext) => 
      engine.encrypt(plaintext, key)
    );
    
    return await Future.wait(futures);
  }
}

Memory Security

// Secure memory handling
class SecureMemory {
  static void clearSensitiveData(Uint8List data) {
    // Overwrite memory with random data
    final random = Random.secure();
    for (int i = 0; i < data.length; i++) {
      data[i] = random.nextInt(256);
    }
    
    // Second pass with zeros
    data.fillRange(0, data.length, 0);
  }
  
  static Uint8List allocateSecure(int size) {
    // In production, use secure memory allocation
    // that prevents swapping to disk
    return Uint8List(size);
  }
}

Monitoring and Alerting

Security Event Monitoring

// Monitor security events
class SecurityMonitor {
  final AuditLogger auditLogger;
  final AlertManager alertManager;
  
  SecurityMonitor({
    required this.auditLogger,
    required this.alertManager,
  });
  
  Future<void> monitorEncryptionEvents() async {
    // Monitor for encryption failures
    final recentLogs = await auditLogger.queryLogs(
      eventType: AuditEventType.securityPolicyChange,
      startTime: DateTime.now().subtract(Duration(hours: 1)),
    );
    
    final failureCount = recentLogs.where((log) => !log.success).length;
    
    if (failureCount > 10) {
      await alertManager.sendAlert(
        SecurityAlert(
          severity: AlertSeverity.high,
          message: 'High encryption failure rate detected',
          details: {'failureCount': failureCount},
        ),
      );
    }
  }
  
  Future<void> monitorKeyRotation() async {
    // Check for overdue key rotations
    final keyInfo = await keyManager.listAllKeys();
    
    for (final entry in keyInfo.entries) {
      final keyId = entry.key;
      final info = entry.value;
      
      if (info['needsRotation'] == true) {
        await alertManager.sendAlert(
          SecurityAlert(
            severity: AlertSeverity.medium,
            message: 'Key rotation overdue',
            details: {'keyId': keyId, 'createdAt': info['createdAt']},
          ),
        );
      }
    }
  }
}

Summary

Vektagraf's security architecture provides comprehensive protection through:

  • Multi-layered encryption with AES-256-GCM and ChaCha20-Poly1305
  • Hierarchical key management with automatic rotation
  • Homomorphic encryption for privacy-preserving computations
  • Field-level encryption with role-based access control
  • Selective disclosure with zero-knowledge proofs
  • Advanced features like differential privacy and secure multi-party computation

Key Takeaways

  1. Defense in Depth: Multiple security layers provide comprehensive protection
  2. Encryption Everywhere: Data is encrypted at rest, in transit, and during computation
  3. Key Management: Proper key rotation and hierarchical derivation are essential
  4. Privacy Preservation: Homomorphic encryption enables secure analytics
  5. Granular Control: Field-level encryption and selective disclosure provide fine-grained access control

Next Steps

  • Chapter 9: Learn about access control and authentication systems
  • Chapter 10: Explore privacy-preserving features and compliance
  • Chapter 11: Understand multi-tenant security architecture