aesCbc static method

Uint8List aesCbc(
  1. Uint8List key,
  2. Uint8List iv,
  3. Uint8List sourceText,
  4. bool encrypt,
)

Encrypts/Decrypts sourceText with symmetric key and initialization vector iv.

To encrypt, set encrypt to true. To decrypt, set encrypt to false.

Implementation

static Uint8List aesCbc(
  final Uint8List key,
  final Uint8List iv,
  final Uint8List sourceText,
  final bool encrypt,
) {
  if (![16, 24, 32].contains(key.length)) {
    throw ArgumentError('key.length must be 16, 24, or 32.');
  }
  if (iv.length != 16) {
    throw ArgumentError('iv.length must be 16.');
  }
  if (sourceText.length % 16 != 0) {
    throw ArgumentError('sourceText.length must be a multiple of 16.');
  }
  final CBCBlockCipher cbc = CBCBlockCipher(AESEngine())
    ..init(encrypt, ParametersWithIV(KeyParameter(key), iv));

  final Uint8List targetText = Uint8List(sourceText.length);

  int offset = 0;
  while (offset < sourceText.length) {
    offset += cbc.processBlock(sourceText, offset, targetText, offset);
  }
  if (sourceText.length != offset) {
    throw ArgumentError('sourceText.length must be equal to offset.');
  }
  return targetText;
}