You are here

public static function ParagonIE_Sodium_Core_Base64_UrlSafe::decode in Automatic Updates 7

Same name and namespace in other branches
  1. 8 vendor/paragonie/sodium_compat/src/Core/Base64/UrlSafe.php \ParagonIE_Sodium_Core_Base64_UrlSafe::decode()

decode from base64 into binary

Base64 character set "./[A-Z][a-z][0-9]"

@psalm-suppress RedundantCondition

Parameters

string $src:

bool $strictPadding:

Return value

string

Throws

RangeException

TypeError

1 call to ParagonIE_Sodium_Core_Base64_UrlSafe::decode()
ParagonIE_Sodium_Compat::base642bin in vendor/paragonie/sodium_compat/src/Compat.php

File

vendor/paragonie/sodium_compat/src/Core/Base64/UrlSafe.php, line 102

Class

ParagonIE_Sodium_Core_Base64_UrlSafe
Class ParagonIE_Sodium_Core_Base64UrlSafe

Code

public static function decode($src, $strictPadding = false) {

  // Remove padding
  $srcLen = ParagonIE_Sodium_Core_Util::strlen($src);
  if ($srcLen === 0) {
    return '';
  }
  if ($strictPadding) {
    if (($srcLen & 3) === 0) {
      if ($src[$srcLen - 1] === '=') {
        $srcLen--;
        if ($src[$srcLen - 1] === '=') {
          $srcLen--;
        }
      }
    }
    if (($srcLen & 3) === 1) {
      throw new RangeException('Incorrect padding');
    }
    if ($src[$srcLen - 1] === '=') {
      throw new RangeException('Incorrect padding');
    }
  }
  else {
    $src = rtrim($src, '=');
    $srcLen = ParagonIE_Sodium_Core_Util::strlen($src);
  }
  $err = 0;
  $dest = '';

  // Main loop (no padding):
  for ($i = 0; $i + 4 <= $srcLen; $i += 4) {

    /** @var array<int, int> $chunk */
    $chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, 4));
    $c0 = self::decode6Bits($chunk[1]);
    $c1 = self::decode6Bits($chunk[2]);
    $c2 = self::decode6Bits($chunk[3]);
    $c3 = self::decode6Bits($chunk[4]);
    $dest .= pack('CCC', ($c0 << 2 | $c1 >> 4) & 0xff, ($c1 << 4 | $c2 >> 2) & 0xff, ($c2 << 6 | $c3) & 0xff);
    $err |= ($c0 | $c1 | $c2 | $c3) >> 8;
  }

  // The last chunk, which may have padding:
  if ($i < $srcLen) {

    /** @var array<int, int> $chunk */
    $chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, $srcLen - $i));
    $c0 = self::decode6Bits($chunk[1]);
    if ($i + 2 < $srcLen) {
      $c1 = self::decode6Bits($chunk[2]);
      $c2 = self::decode6Bits($chunk[3]);
      $dest .= pack('CC', ($c0 << 2 | $c1 >> 4) & 0xff, ($c1 << 4 | $c2 >> 2) & 0xff);
      $err |= ($c0 | $c1 | $c2) >> 8;
    }
    elseif ($i + 1 < $srcLen) {
      $c1 = self::decode6Bits($chunk[2]);
      $dest .= pack('C', ($c0 << 2 | $c1 >> 4) & 0xff);
      $err |= ($c0 | $c1) >> 8;
    }
    elseif ($i < $srcLen && $strictPadding) {
      $err |= 1;
    }
  }

  /** @var bool $check */
  $check = $err === 0;
  if (!$check) {
    throw new RangeException('Base64::decode() only expects characters in the correct base64 alphabet');
  }
  return $dest;
}