preWrite method

  1. @override
void preWrite(
  1. PHiveCtx ctx
)

Encrypts the current string value and stores the IV in PHive metadata.

Implementation

@override
/// Encrypts the current string value and stores the IV in PHive metadata.
void preWrite(PHiveCtx ctx) {
  if (ctx.value is! String) return;

  final plaintext = utf8.encode(ctx.value as String);
  final iv = _createIv();
  ctx.pendingMetadata[_ivMetadataKey] = base64Url.encode(iv);

  final key = PhiveMetaRegistry.requireSeedSync(seedId);
  final paddedPlaintext = _padPlaintext(plaintext);
  final cipher = _buildCipher(true, key, iv);

  final ciphertext = Uint8List(paddedPlaintext.length);
  for (var offset = 0; offset < paddedPlaintext.length; offset += _blockSize) {
    cipher.processBlock(paddedPlaintext, offset, ciphertext, offset);
  }

  ctx.value = base64Url.encode(ciphertext);
}