write method

  1. @override
Future<void> write(
  1. Uint8List data
)
override

Writes data to the connection.

Implementation

@override
Future<void> write(Uint8List data) async {
  // ADDED LOGGING: Print the initial plaintext data received by write()

  _log.finer('SecuredConnection.write: Plaintext data received (length: ${data.length}, first 20 bytes: ${data.take(20).toList()})');
  _log.finer('SecuredConnection: Writing data of length ${data.length}');
  final algorithm = crypto.Chacha20.poly1305Aead();
  final nonce = _getNonce(_sendNonce++);
  _log.finer('SecuredConnection: Using nonce: ${nonce.toList()}');
  // ADDED LOGGING for hashCode
  _log.finer('SecuredConnection: Using encryption key (hashCode: ${_encryptionKey.hashCode}): ${await _encryptionKey.extractBytes()}');

  final secretBox = await algorithm.encrypt(
    data,
    secretKey: _encryptionKey,
    nonce: nonce,
    aad: Uint8List(0),
  );


  // Calculate total length of encrypted data + MAC
  final dataLength = secretBox.cipherText.length + secretBox.mac.bytes.length;
  _log.finer('SecuredConnection: Encrypted data length: ${secretBox.cipherText.length}');
  _log.finer('SecuredConnection: MAC length: ${secretBox.mac.bytes.length}');
  _log.finer('SecuredConnection: MAC: ${secretBox.mac.bytes.toList()}');
  _log.finer('SecuredConnection:   Raw Ciphertext to send: ${hex.encode(secretBox.cipherText)}');
  _log.finer('SecuredConnection:   Raw MAC to send: ${hex.encode(secretBox.mac.bytes)}');


  // Write length prefix and data in one operation
  final combinedData = Uint8List(2 + dataLength)
  // Write length prefix (2 bytes)
    ..[0] = dataLength >> 8
    ..[1] = dataLength & 0xFF
  // Write encrypted data
    ..setAll(2, secretBox.cipherText)
  // Write MAC
    ..setAll(2 + secretBox.cipherText.length, secretBox.mac.bytes);

  _log.finer('SecuredConnection: Writing ${data.length} bytes as ${dataLength} bytes encrypted+MAC');
  _log.finer('SecuredConnection:   Raw Ciphertext to send: ${hex.encode(secretBox.cipherText)}');
  _log.finer('SecuredConnection:   Raw MAC to send: ${hex.encode(secretBox.mac.bytes)}');
  _log.finer('SecuredConnection: First 4 bytes of encrypted: ${secretBox.cipherText.take(4).toList()}');
  _log.finer('SecuredConnection: TO_UNDERLYING_WRITE - Length: ${combinedData.length}, Bytes: ${hex.encode(combinedData)}');
  await _connection.write(combinedData);
}