createEncryptionDecryptHook function
Creates a hook that decrypts entry values after retrieval.
Implementation
PVCacheHook createEncryptionDecryptHook({
String? encryptionKey,
String keyName = DEFAULT_ENCRYPTION_KEY_NAME,
int priority = 0,
}) {
return PVCacheHook(
eventString: 'encryption_decrypt',
eventFlow: EventFlow.postProcess,
priority: priority,
actionTypes: [ActionType.get, ActionType.exists],
hookFunction: (ctx) async {
// Skip if no value or not encrypted
if (ctx.entryValue == null) return;
if (ctx.runtimeMeta['_encrypted'] != true) return;
// Get encryption key
final key = encryptionKey ?? await getOrCreateEncryptionKey(keyName);
final cipher = AESCipher(key);
try {
// Decrypt
final decrypted = cipher.decryptString(ctx.entryValue as String);
// Parse JSON back to original value
ctx.entryValue = jsonDecode(decrypted);
} catch (e) {
// If decryption fails, leave as null
ctx.entryValue = null;
throw Exception('Warning: Failed to decrypt entry: $e');
}
},
);
}