/** * PKCS #7 unpadding function. * * @param string $input Padded string to unpad * * @return string */ public static function unpad($input) { // Determine the padding size by converting the final byte of the // input to its decimal value $padsize = \ord(Str::substr($input, -1)); // Return string minus the padding amount return Str::substr($input, 0, Str::strlen($input) - $padsize); }
/** * This will normalize a hash to a certain length by extending it if * too short and truncating it if too long. This ensures that any * hash algo will work with any combination of other settings. However, * it is probably best to make sure that the keysize and algo size * are identical so that the input hash passes through unchanged. * * @param string $hash Hash to be normalized * @param int $size Size of the desired output hash, in bytes * @param string $algo Hashing algorithm to use for internal operations * * @return string */ private static function hashNormalize($hash, $size, $algo) { // Extend hash if too short while (Str::strlen($hash) < $size) { $hash .= \hash($algo, $hash, true); } // Truncate to specified number of bytes (if needed) and return return Str::substr($hash, 0, $size); }
/** * Create the initial byte matrix that will be used for swaps. This code * is identical between RC4 and Spritz. * * @param string $key * * @return array */ protected static function initializeState($key) { $s = \range(0, 255); $j = 0; foreach (\range(0, 255) as $i) { $j = ($j + $s[$i] + \ord($key[$i % Str::strlen($key)])) % 256; $x = $s[$i]; $s[$i] = $s[$j]; $s[$j] = $x; } return $s; }
/** * Perform (en/de)cryption * * @param string $str String to be encrypted * @param string $key Key to use for encryption * * @return string */ public static function crypt($str, $key) { $s = self::initializeState($key); $i = $j = $k = $z = 0; $w = 1; $res = ''; $size = Str::strlen($str); for ($y = 0; $y < $size; $y++) { $i = ($i + $w) % 256; $j = ($k + $s[($j + $s[$i]) % 256]) % 256; $k = ($i + $k + $s[$j]) % 256; $x = $s[$i]; $s[$i] = $s[$j]; $s[$j] = $x; $z = $s[($j + $s[($i + $s[($z + $k) % 256]) % 256]) % 256]; $res .= $str[$y] ^ \chr($z); } return $res; }