createEncryptionEncryptHook function

PVCacheHook createEncryptionEncryptHook({
  1. String? encryptionKey,
  2. String keyName = DEFAULT_ENCRYPTION_KEY_NAME,
  3. int priority = -50,
})

Encryption Hook System

Automatic encryption/decryption using AES-256-CTR.

Features:

  • AES-256-CTR (no padding, handles any length)
  • Auto key generation and secure storage
  • Deterministic IV for consistent caching
  • Cross-platform
  • Base64 encoding

Usage:

// Auto-generate key
final cache = PVCache(
  env: 'myCache',
  hooks: createEncryptionHooks(),
  defaultMetadata: {},
);

// Custom key
final cache = PVCache(
  env: 'myCache',
  hooks: createEncryptionHooks(encryptionKey: 'my-secret-key'),
  defaultMetadata: {},
);

Creates a hook that encrypts entry values before storage.

Implementation

/// Creates a hook that encrypts entry values before storage.
PVCacheHook createEncryptionEncryptHook({
  String? encryptionKey,
  String keyName = DEFAULT_ENCRYPTION_KEY_NAME,
  int priority = -50,
}) {
  return PVCacheHook(
    eventString: 'encryption_encrypt',
    eventFlow: EventFlow.storageUpdate,
    priority: priority,
    actionTypes: [ActionType.put],
    hookFunction: (ctx) async {
      // Skip if no value
      if (ctx.entryValue == null) return;

      // Get or create encryption key
      final key = encryptionKey ?? await getOrCreateEncryptionKey(keyName);
      final cipher = AESCipher(key);

      // Convert value to JSON string
      final jsonString = jsonEncode(ctx.entryValue);

      // Encrypt
      final encrypted = cipher.encryptString(jsonString);

      // Replace entry value with encrypted version
      ctx.entryValue = encrypted;

      // Mark in metadata that this entry is encrypted
      ctx.runtimeMeta['_encrypted'] = true;
    },
  );
}