encryptStringWithNonce method

String encryptStringWithNonce(
  1. String data,
  2. String nonce
)

Encrypt with random nonce (for selective encryption).

Implementation

String encryptStringWithNonce(String data, String nonce) {
  final plainBytes = utf8.encode(data);

  // Generate IV from nonce
  final iv = _generateNonceIV(nonce);

  // Handle empty string case
  if (plainBytes.isEmpty) {
    return base64.encode(iv);
  }

  // Setup AES cipher in CTR mode
  final cipher = CTRStreamCipher(AESEngine());
  final params = ParametersWithIV(KeyParameter(_key), iv);

  cipher.init(true, params); // true = encrypt

  final encryptedBytes = cipher.process(Uint8List.fromList(plainBytes));

  // Combine IV + encrypted data
  final result = Uint8List(iv.length + encryptedBytes.length);
  result.setRange(0, iv.length, iv);
  result.setRange(iv.length, result.length, encryptedBytes);

  return base64.encode(result);
}