You are here

public static function ParagonIE_Sodium_Compat::unpad in Automatic Updates 7

Same name and namespace in other branches
  1. 8 vendor/paragonie/sodium_compat/src/Compat.php \ParagonIE_Sodium_Compat::unpad()

Parameters

string $padded:

int $blockSize:

bool $dontFallback:

Return value

string

Throws

SodiumException

1 call to ParagonIE_Sodium_Compat::unpad()
php72compat.php in vendor/paragonie/sodium_compat/lib/php72compat.php

File

vendor/paragonie/sodium_compat/src/Compat.php, line 3309

Class

ParagonIE_Sodium_Compat

Code

public static function unpad($padded, $blockSize, $dontFallback = false) {

  /* Type checks: */
  ParagonIE_Sodium_Core_Util::declareScalarType($padded, 'string', 1);
  ParagonIE_Sodium_Core_Util::declareScalarType($blockSize, 'int', 2);
  $padded = (string) $padded;
  $blockSize = (int) $blockSize;
  if (self::useNewSodiumAPI() && !$dontFallback) {
    return (string) sodium_unpad($padded, $blockSize);
  }
  if ($blockSize <= 0) {
    throw new SodiumException('block size cannot be less than 1');
  }
  $padded_len = ParagonIE_Sodium_Core_Util::strlen($padded);
  if ($padded_len < $blockSize) {
    throw new SodiumException('invalid padding');
  }

  # tail = &padded[padded_len - 1U];
  $tail = $padded_len - 1;
  $acc = 0;
  $valid = 0;
  $pad_len = 0;
  $found = 0;
  for ($i = 0; $i < $blockSize; ++$i) {

    # c = tail[-i];
    $c = ParagonIE_Sodium_Core_Util::chrToInt($padded[$tail - $i]);

    # is_barrier =

    #     (( (acc - 1U) & (pad_len - 1U) & ((c ^ 0x80) - 1U) ) >> 8) & 1U;
    $is_barrier = ($acc - 1 & $pad_len - 1 & ($c ^ 80) - 1) >> 7 & 1;
    $is_barrier &= ~$found;
    $found |= $is_barrier;

    # acc |= c;
    $acc |= $c;

    # pad_len |= i & (1U + ~is_barrier);
    $pad_len |= $i & 1 + ~$is_barrier;

    # valid |= (unsigned char) is_barrier;
    $valid |= $is_barrier & 0xff;
  }

  # unpadded_len = padded_len - 1U - pad_len;
  $unpadded_len = $padded_len - 1 - $pad_len;
  if ($valid !== 1) {
    throw new SodiumException('invalid padding');
  }
  return ParagonIE_Sodium_Core_Util::substr($padded, 0, $unpadded_len);
}