unpad static method

BuBytes unpad(
  1. List<int> paddedData,
  2. int blockSize, {
  3. PaddingAlgorithm style = PaddingAlgorithm.pkcs7,
})

Removes style padding from paddedData.

Throws CryptoException if paddedData is empty, isn't a multiple of blockSize, or doesn't end in valid padding.

Implementation

static BuBytes unpad(
  List<int> paddedData,
  int blockSize, {
  PaddingAlgorithm style = PaddingAlgorithm.pkcs7,
}) {
  final n = paddedData.length;

  // These two checks are on PUBLIC information (the ciphertext's own
  // length, and the block size) - not the secret padding content - so
  // branching on them doesn't leak anything about the plaintext.
  if (n == 0) {
    throw CoreErrors.cryptoFailed(
      'unpad',
      reason: "Zero-length input cannot be unpadded.",
    );
  }
  if (n % blockSize != 0) {
    throw CoreErrors.cryptoFailed(
      "unpad",
      reason: "Input data is not padded.",
    );
  }

  final (int paddingLen, bool ok) result;
  switch (style) {
    case PaddingAlgorithm.pkcs7:
      final claimed = paddedData[n - 1];
      result = _selectValidLength(blockSize, (candidateLen) {
        var valid = 1;
        for (var i = 0; i < candidateLen; i++) {
          valid &= _ctByteEq(paddedData[n - 1 - i], candidateLen);
        }
        return valid & _ctByteEq(claimed, candidateLen);
      });
      break;

    case PaddingAlgorithm.x923:
      result = _selectValidLength(blockSize, (candidateLen) {
        var valid = _ctByteEq(paddedData[n - 1], candidateLen);
        for (var i = 1; i < candidateLen; i++) {
          valid &= _ctByteEq(paddedData[n - 1 - i], 0);
        }
        return valid;
      });
      break;

    case PaddingAlgorithm.iso7816:
      result = _selectValidLength(blockSize, (candidateLen) {
        final firstPadPos = n - candidateLen;
        var valid = _ctByteEq(paddedData[firstPadPos], 0x80);
        for (var i = 1; i < candidateLen; i++) {
          valid &= _ctByteEq(paddedData[firstPadPos + i], 0);
        }
        return valid;
      });
      break;
  }

  if (!result.$2) {
    throw CoreErrors.cryptoFailed("unpad", reason: "Incorrect padding.");
  }
  return BuBytes(paddedData.sublist(0, n - result.$1));
}