encryptStream abstract method

Stream<Uint8List> encryptStream(
  1. Stream<List<int>> data,
  2. List<int> iv
)

Encrypt data with this AesCbcSecretKey using AES in Cipher Block Chaining mode, as specified in NIST SP800-38A.

The operation requires a 16 bytes initalization vector iv. The iv needs not be secret, but it must be unpredictable. In particular, for a given plaintext it must not be possible to predict the iv that will be used to encrypt the plaintext. For detailed discussion of the initialization vector requirements for AES-CBC, see Appendix C of NIST SP800-38A.

Encrypted output is always padded in PKCS#7 mode, as described in RFC 2315 Section 10.3 step 2. This padding is stripped when the message is decrypted.

Example

import 'dart:io' show File;
import 'dart:convert' show utf8;
import 'dart:typed_data' show Uint8List;
import 'package:async/async.dart' show collectBytes;
import 'package:webcrypto/webcrypto.dart';

// Generate a new random AES-CBC secret key for AES-256.
final k = await AesCbcSecretKey.generate(256);

// Use a unique IV for each message.
final iv = Uint8List(16);
fillRandomBytes(iv);

// Encrypt a message from file and write to file
final inputFile = File('message.txt');
final encryptedFile = File('encrypted-message.binary');
final c = await k.encryptStream(
  inputFile.openRead(),
  iv,
).pipe(encryptedFile.openWrite());

// Decrypt message (requires the same iv)
final decryptedBytes = await collectBytes(k.decryptStream(
  encryptedFile.openRead(),
  iv, // same iv as used for encryption
));
// decryptedBytes should be equal to contents of inputFile
assert(utf8.decode(decryptedBytes) == inputFile.readAsStringSync());

Implementation

Stream<Uint8List> encryptStream(Stream<List<int>> data, List<int> iv);