You are here

public static function ParagonIE_Sodium_Compat::pad in Automatic Updates 8

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

Parameters

string $unpadded:

int $blockSize:

bool $dontFallback:

Return value

string

Throws

SodiumException

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

File

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

Class

ParagonIE_Sodium_Compat

Code

public static function pad($unpadded, $blockSize, $dontFallback = false) {

  /* Type checks: */
  ParagonIE_Sodium_Core_Util::declareScalarType($unpadded, 'string', 1);
  ParagonIE_Sodium_Core_Util::declareScalarType($blockSize, 'int', 2);
  $unpadded = (string) $unpadded;
  $blockSize = (int) $blockSize;
  if (self::useNewSodiumAPI() && !$dontFallback) {
    return (string) sodium_pad($unpadded, $blockSize);
  }
  if ($blockSize <= 0) {
    throw new SodiumException('block size cannot be less than 1');
  }
  $unpadded_len = ParagonIE_Sodium_Core_Util::strlen($unpadded);
  $xpadlen = $blockSize - 1;
  if (($blockSize & $blockSize - 1) === 0) {
    $xpadlen -= $unpadded_len & $blockSize - 1;
  }
  else {
    $xpadlen -= $unpadded_len % $blockSize;
  }
  $xpadded_len = $unpadded_len + $xpadlen;
  $padded = str_repeat("\0", $xpadded_len - 1);
  if ($unpadded_len > 0) {
    $st = 1;
    $i = 0;
    $k = $unpadded_len;
    for ($j = 0; $j <= $xpadded_len; ++$j) {
      $i = (int) $i;
      $k = (int) $k;
      $st = (int) $st;
      if ($j >= $unpadded_len) {
        $padded[$j] = "\0";
      }
      else {
        $padded[$j] = $unpadded[$j];
      }

      /** @var int $k */
      $k -= $st;
      $st = (int) ~(($k >> 48 | $k >> 32 | $k >> 16 | $k) - 1 >> 16) & 1;
      $i += $st;
    }
  }
  $mask = 0;
  $tail = $xpadded_len;
  for ($i = 0; $i < $blockSize; ++$i) {

    # barrier_mask = (unsigned char)

    #     (((i ^ xpadlen) - 1U) >> ((sizeof(size_t) - 1U) * CHAR_BIT));
    $barrier_mask = ($i ^ $xpadlen) - 1 >> (PHP_INT_SIZE << 3) - 1;

    # tail[-i] = (tail[-i] & mask) | (0x80 & barrier_mask);
    $padded[$tail - $i] = ParagonIE_Sodium_Core_Util::intToChr(ParagonIE_Sodium_Core_Util::chrToInt($padded[$tail - $i]) & $mask | 0x80 & $barrier_mask);

    # mask |= barrier_mask;
    $mask |= $barrier_mask;
  }
  return $padded;
}