pad static method

List<int> pad(
  1. List<int> dataToPad,
  2. int blockSize, {
  3. PaddingAlgorithm style = PaddingAlgorithm.pkcs7,
})

Adds padding to the provided data to match the specified block size.

This method adds padding to the input data to make its length a multiple of the specified block size. The padding style can be selected from the available padding algorithms.

Parameters:

  • dataToPad: The input data to be padded.
  • blockSize: The desired block size for the data.
  • style: The padding style, which can be one of the PaddingAlgorithm values (default is pkcs7).

Returns:

  • A new List<int> containing the input data with the added padding.

Implementation

static List<int> pad(List<int> dataToPad, int blockSize,
    {PaddingAlgorithm style = PaddingAlgorithm.pkcs7}) {
  int paddingLen = blockSize - dataToPad.length % blockSize;
  List<int> padding;

  if (style == PaddingAlgorithm.pkcs7) {
    padding = List<int>.filled(paddingLen, 0);
    for (int i = 0; i < paddingLen; i++) {
      padding[i] = paddingLen;
    }
  } else if (style == PaddingAlgorithm.x923) {
    padding = List<int>.filled(paddingLen, 0);
    for (int i = 0; i < paddingLen - 1; i++) {
      padding[i] = 0;
    }
    padding[paddingLen - 1] = paddingLen;
  } else {
    padding = List<int>.filled(paddingLen, 0);
    padding[0] = 128;
    for (int i = 1; i < paddingLen; i++) {
      padding[i] = 0;
    }
  }

  List<int> result = List<int>.filled(dataToPad.length + paddingLen, 0);
  result.setAll(0, dataToPad);
  result.setAll(dataToPad.length, padding);

  return result;
}