encrypt method

Uint8List encrypt(
  1. BlockCipher cipher,
  2. dynamic input, {
  3. Iterable<int>? iv,
  4. Padder padder = const PKCS7Padder(),
})

Implementation

Uint8List encrypt(BlockCipher cipher, input,
    {Iterable<int>? iv, Padder padder = const PKCS7Padder()}) {
  Iterable<int> mangler;
  if (iv != null) {
    if (iv.length != cipher.blockSize) {
      throw Exception('Invalid initial vector length');
    }
    mangler = iv;
  } else {
    mangler = Uint8List(cipher.blockSize);
  }

  if (input is String) {
    input = utf8.encode(input);
  }
  final padded = padder.pad(cipher.blockSize, input);

  final numBlocks = (padded.length / cipher.blockSize).ceil();
  final out = Uint8List(numBlocks * cipher.blockSize);

  int offset = 0;
  for (int i = 0; i < numBlocks; i++) {
    final inputBlock =
        ListOps.xor(padded.skip(offset).take(cipher.blockSize), mangler)
            .buffer
            .asByteData();
    final outputBlock = out.buffer.asByteData(offset, cipher.blockSize);
    cipher.processBlock(inputBlock, outputBlock);
    mangler = out.skip(offset).take(cipher.blockSize);
    offset += cipher.blockSize;
  }

  return out;
}