Merge branch '3.0'

This commit is contained in:
terrafrost 2022-02-19 18:08:40 -06:00
commit 004aec954f
208 changed files with 1301 additions and 1182 deletions

View File

@ -33,7 +33,7 @@ install:
- travis/setup-composer.sh - travis/setup-composer.sh
script: script:
- sh -c "if [ '$TRAVIS_PHP_VERSION' = '5.5' ]; then vendor/bin/phing -f build/build.xml sniff; fi" - sh -c "if [ -d build/vendor ]; then build/vendor/bin/phpcs --standard=build/phpcs_ruleset.xml; fi"
- sh -c "if [ -d build/vendor ]; then build/vendor/bin/php-cs-fixer fix --config=build/php-cs-fixer.php --diff --dry-run; fi" - sh -c "if [ -d build/vendor ]; then build/vendor/bin/php-cs-fixer fix --config=build/php-cs-fixer.php --diff --dry-run; fi"
- sh -c "if [ -d build/vendor ]; then build/vendor/bin/psalm --config="build/psalm.xml" --no-cache --long-progress --report-show-info=false --output-format=text; fi" - sh -c "if [ -d build/vendor ]; then build/vendor/bin/psalm --config="build/psalm.xml" --no-cache --long-progress --report-show-info=false --output-format=text; fi"
- travis/run-phpunit.sh - travis/run-phpunit.sh

View File

@ -82,6 +82,7 @@ Special Thanks to our $50+ sponsors!:
3. Install Development Dependencies 3. Install Development Dependencies
```sh ```sh
composer install composer install
composer install --no-interaction --working-dir=build
``` ```
4. Create a Feature Branch 4. Create a Feature Branch
@ -89,10 +90,9 @@ Special Thanks to our $50+ sponsors!:
5. Run continuous integration checks: 5. Run continuous integration checks:
```sh ```sh
vendor/bin/phpunit vendor/bin/phpunit
vendor/bin/phing -f build/build.xml sniff
# The following tools are from the build specific composer.json: # The following tools are from the build specific composer.json using the most recent PHP version:
composer install --no-interaction --working-dir=build build/vendor/bin/phpcs --standard=build/phpcs_ruleset.xml
build/vendor/bin/php-cs-fixer fix --config=build/php-cs-fixer.php --diff --dry-run build/vendor/bin/php-cs-fixer fix --config=build/php-cs-fixer.php --diff --dry-run
build/vendor/bin/psalm --config=build/psalm.xml --no-cache --long-progress --report-show-info=false --output-format=text build/vendor/bin/psalm --config=build/psalm.xml --no-cache --long-progress --report-show-info=false --output-format=text
``` ```

View File

@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="phpseclib"
description="PHP Secure Communications Library"
default="all"
>
<target name="all" depends="sniff" />
<!-- Code Sniffer -->
<target name="sniff" depends="sniff-php-code,sniff-php-tests" />
<target name="sniff-php-code">
<exec command="vendor/bin/phpcs -s
--extensions=php
--standard=build/code-sniffer-ruleset.xml
phpseclib/"
dir=".." checkreturn="true" passthru="true" />
</target>
<target name="sniff-php-tests">
<exec command="vendor/bin/phpcs -s
--extensions=php
--standard=build/code-sniffer-ruleset-tests.xml
tests/"
dir=".." checkreturn="true" passthru="true" />
</target>
</project>

View File

@ -1,17 +0,0 @@
<?xml version="1.0"?>
<ruleset name="phpseclib Test Standard">
<description>phpseclib coding standard for tests</description>
<!-- In general rules that apply to library code also apply to tests. -->
<rule ref="./code-sniffer-ruleset.xml">
<!-- Exceptions to the library coding standard follow. -->
<!-- Test classes do not have to be namespaced but may use pseudo-namespacing
using underscore. -->
<exclude name="PSR1.Classes.ClassDeclaration.MissingNamespace" />
<exclude name="Squiz.Classes.ValidClassName.NotCamelCaps" />
<exclude name="PSR1.Files.SideEffects.FoundWithSymbols" />
</rule>
</ruleset>

View File

@ -1,35 +0,0 @@
<?xml version="1.0"?>
<ruleset name="phpseclib Standard">
<description>phpseclib coding standard</description>
<!-- We are using the PSR2 standard as a base -->
<rule ref="PSR2">
<!-- Exceptions due to legacy code with PHP4 compatibility -->
<exclude name="PSR2.Classes.PropertyDeclaration.ScopeMissing" />
<exclude name="PSR2.Classes.PropertyDeclaration.VarUsed" />
<exclude name="Squiz.Scope.MethodScope.Missing" />
<!-- Exceptions for backward compatibility -->
<exclude name="PSR1.Methods.CamelCapsMethodName.NotCamelCaps" />
<exclude name="PSR2.Methods.MethodDeclaration.Underscore" />
<!-- Exceptions for whitespacing -->
<exclude name="Generic.Functions.FunctionCallArgumentSpacing.TooMuchSpaceAfterComma" />
<exclude name="PSR2.ControlStructures.SwitchDeclaration.SpaceBeforeColonCASE" />
<exclude name="PSR2.ControlStructures.SwitchDeclaration.SpaceBeforeColonDEFAULT" />
<!-- Other Exceptions -->
<exclude name="Generic.Files.LineLength.TooLong" />
<exclude name="PSR2.ControlStructures.SwitchDeclaration.TerminatingComment" />
</rule>
<!-- Useful additional rules follow -->
<!-- "for (; bar; )" should be "while (bar)" instead -->
<rule ref="Generic.CodeAnalysis.ForLoopShouldBeWhileLoop" />
<!-- A method MUST not only call its parent -->
<rule ref="Generic.CodeAnalysis.UselessOverridingMethod" />
</ruleset>

View File

@ -6,6 +6,7 @@
"require": { "require": {
"php": "^8.1.0", "php": "^8.1.0",
"friendsofphp/php-cs-fixer": "^3.5", "friendsofphp/php-cs-fixer": "^3.5",
"squizlabs/php_codesniffer": "^3.6",
"vimeo/psalm": "^4.19" "vimeo/psalm": "^4.19"
}, },
"config": { "config": {

22
build/phpcs_ruleset.xml Normal file
View File

@ -0,0 +1,22 @@
<?xml version="1.0"?>
<ruleset name="phpseclib">
<file>../build/php-cs-fixer.php</file>
<file>../phpseclib/</file>
<file>../tests/</file>
<arg name="extensions" value="php"/>
<arg name="basepath" value=".."/>
<arg name="report" value="emacs"/>
<arg value="s"/>
<arg value="n"/>
<arg value="p"/>
<rule ref="PSR12">
<exclude name="Squiz.Classes.ValidClassName.NotCamelCaps"/>
<exclude name="PSR1.Methods.CamelCapsMethodName.NotCamelCaps"/>
<exclude name="PSR2.Methods.MethodDeclaration.Underscore"/>
<exclude name="PSR2.ControlStructures.SwitchDeclaration.TerminatingComment"/>
<exclude name="PSR1.Classes.ClassDeclaration.MissingNamespace"/>
<exclude name="PSR1.Classes.ClassDeclaration.MultipleClasses"/>
</rule>
</ruleset>

View File

@ -56,9 +56,7 @@
"php": ">=5.6.1" "php": ">=5.6.1"
}, },
"require-dev": { "require-dev": {
"phing/phing": "~2.7", "phpunit/phpunit": "^5.7|^6.0|^9.4"
"phpunit/phpunit": "^5.7|^6.0|^9.4",
"squizlabs/php_codesniffer": "~2.0"
}, },
"suggest": { "suggest": {
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",

View File

@ -130,7 +130,7 @@ abstract class Strings
// you need > 32-bit precision doesn't mean you need the full 64-bit precision // you need > 32-bit precision doesn't mean you need the full 64-bit precision
extract(unpack('Nupper/Nlower', self::shift($data, 8))); extract(unpack('Nupper/Nlower', self::shift($data, 8)));
$temp = $upper ? 4294967296 * $upper : 0; $temp = $upper ? 4294967296 * $upper : 0;
$temp+= $lower < 0 ? ($lower & 0x7FFFFFFFF) + 0x80000000 : $lower; $temp += $lower < 0 ? ($lower & 0x7FFFFFFFF) + 0x80000000 : $lower;
// $temp = hexdec(bin2hex(self::shift($data, 8))); // $temp = hexdec(bin2hex(self::shift($data, 8)));
$result[] = $temp; $result[] = $temp;
continue 2; continue 2;
@ -177,20 +177,20 @@ abstract class Strings
if (!is_int($element)) { if (!is_int($element)) {
throw new \InvalidArgumentException('Bytes must be represented as an integer between 0 and 255, inclusive.'); throw new \InvalidArgumentException('Bytes must be represented as an integer between 0 and 255, inclusive.');
} }
$result.= pack('C', $element); $result .= pack('C', $element);
break; break;
case 'b': case 'b':
if (!is_bool($element)) { if (!is_bool($element)) {
throw new \InvalidArgumentException('A boolean parameter was expected.'); throw new \InvalidArgumentException('A boolean parameter was expected.');
} }
$result.= $element ? "\1" : "\0"; $result .= $element ? "\1" : "\0";
break; break;
case 'Q': case 'Q':
if (!is_int($element) && !is_float($element)) { if (!is_int($element) && !is_float($element)) {
throw new \InvalidArgumentException('An integer was expected.'); throw new \InvalidArgumentException('An integer was expected.');
} }
// 4294967296 == 1 << 32 // 4294967296 == 1 << 32
$result.= pack('NN', $element / 4294967296, $element); $result .= pack('NN', $element / 4294967296, $element);
break; break;
case 'N': case 'N':
if (is_float($element)) { if (is_float($element)) {
@ -199,27 +199,27 @@ abstract class Strings
if (!is_int($element)) { if (!is_int($element)) {
throw new \InvalidArgumentException('An integer was expected.'); throw new \InvalidArgumentException('An integer was expected.');
} }
$result.= pack('N', $element); $result .= pack('N', $element);
break; break;
case 's': case 's':
if (!self::is_stringable($element)) { if (!self::is_stringable($element)) {
throw new \InvalidArgumentException('A string was expected.'); throw new \InvalidArgumentException('A string was expected.');
} }
$result.= pack('Na*', strlen($element), $element); $result .= pack('Na*', strlen($element), $element);
break; break;
case 'i': case 'i':
if (!$element instanceof BigInteger && !$element instanceof FiniteField\Integer) { if (!$element instanceof BigInteger && !$element instanceof FiniteField\Integer) {
throw new \InvalidArgumentException('A phpseclib3\Math\BigInteger or phpseclib3\Math\Common\FiniteField\Integer object was expected.'); throw new \InvalidArgumentException('A phpseclib3\Math\BigInteger or phpseclib3\Math\Common\FiniteField\Integer object was expected.');
} }
$element = $element->toBytes(true); $element = $element->toBytes(true);
$result.= pack('Na*', strlen($element), $element); $result .= pack('Na*', strlen($element), $element);
break; break;
case 'L': case 'L':
if (!is_array($element)) { if (!is_array($element)) {
throw new \InvalidArgumentException('An array was expected.'); throw new \InvalidArgumentException('An array was expected.');
} }
$element = implode(',', $element); $element = implode(',', $element);
$result.= pack('Na*', strlen($element), $element); $result .= pack('Na*', strlen($element), $element);
break; break;
default: default:
throw new \InvalidArgumentException('$format contains an invalid character'); throw new \InvalidArgumentException('$format contains an invalid character');
@ -241,10 +241,10 @@ abstract class Strings
{ {
$parts = preg_split('#(\d+)#', $format, -1, PREG_SPLIT_DELIM_CAPTURE); $parts = preg_split('#(\d+)#', $format, -1, PREG_SPLIT_DELIM_CAPTURE);
$format = ''; $format = '';
for ($i = 1; $i < count($parts); $i+=2) { for ($i = 1; $i < count($parts); $i += 2) {
$format.= substr($parts[$i - 1], 0, -1) . str_repeat(substr($parts[$i - 1], -1), $parts[$i]); $format .= substr($parts[$i - 1], 0, -1) . str_repeat(substr($parts[$i - 1], -1), $parts[$i]);
} }
$format.= $parts[$i - 1]; $format .= $parts[$i - 1];
return $format; return $format;
} }
@ -293,7 +293,7 @@ abstract class Strings
foreach ($parts as $part) { foreach ($parts as $part) {
$xor = $part[0] == '1' ? PHP_INT_MIN : 0; $xor = $part[0] == '1' ? PHP_INT_MIN : 0;
$part[0] = '0'; $part[0] = '0';
$str.= pack( $str .= pack(
PHP_INT_SIZE == 4 ? 'N' : 'J', PHP_INT_SIZE == 4 ? 'N' : 'J',
$xor ^ eval('return 0b' . $part . ';') $xor ^ eval('return 0b' . $part . ';')
); );
@ -328,12 +328,12 @@ abstract class Strings
if (PHP_INT_SIZE == 4) { if (PHP_INT_SIZE == 4) {
$digits = unpack('N*', $x); $digits = unpack('N*', $x);
foreach ($digits as $digit) { foreach ($digits as $digit) {
$bits.= sprintf('%032b', $digit); $bits .= sprintf('%032b', $digit);
} }
} else { } else {
$digits = unpack('J*', $x); $digits = unpack('J*', $x);
foreach ($digits as $digit) { foreach ($digits as $digit) {
$bits.= sprintf('%064b', $digit); $bits .= sprintf('%064b', $digit);
} }
} }
@ -355,13 +355,13 @@ abstract class Strings
if (PHP_INT_SIZE === 8) { if (PHP_INT_SIZE === 8) {
// 3 operations // 3 operations
// from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64BitsDiv // from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64BitsDiv
$r.= chr((($b * 0x0202020202) & 0x010884422010) % 1023); $r .= chr((($b * 0x0202020202) & 0x010884422010) % 1023);
} else { } else {
// 7 operations // 7 operations
// from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith32Bits // from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith32Bits
$p1 = ($b * 0x0802) & 0x22110; $p1 = ($b * 0x0802) & 0x22110;
$p2 = ($b * 0x8020) & 0x88440; $p2 = ($b * 0x8020) & 0x88440;
$r.= chr( $r .= chr(
(($p1 | $p2) * 0x10101) >> 16 (($p1 | $p2) * 0x10101) >> 16
); );
} }
@ -385,7 +385,7 @@ abstract class Strings
return $var; return $var;
} }
for ($i = 4; $i <= strlen($var); $i+= 4) { for ($i = 4; $i <= strlen($var); $i += 4) {
$temp = substr($var, -$i, 4); $temp = substr($var, -$i, 4);
switch ($temp) { switch ($temp) {
case "\xFF\xFF\xFF\xFF": case "\xFF\xFF\xFF\xFF":

View File

@ -422,14 +422,14 @@ class Blowfish extends BlockCipher
$l = $in[1]; $l = $in[1];
$r = $in[2]; $r = $in[2];
for ($i = 0; $i < 16; $i+= 2) { for ($i = 0; $i < 16; $i += 2) {
$l^= $p[$i]; $l ^= $p[$i];
$r^= self::safe_intval((self::safe_intval($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]) ^ $r ^= self::safe_intval((self::safe_intval($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]) ^
$sb_2[$l >> 8 & 0xff]) + $sb_2[$l >> 8 & 0xff]) +
$sb_3[$l & 0xff]); $sb_3[$l & 0xff]);
$r^= $p[$i + 1]; $r ^= $p[$i + 1];
$l^= self::safe_intval((self::safe_intval($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]) ^ $l ^= self::safe_intval((self::safe_intval($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]) ^
$sb_2[$r >> 8 & 0xff]) + $sb_2[$r >> 8 & 0xff]) +
$sb_3[$r & 0xff]); $sb_3[$r & 0xff]);
} }
@ -455,14 +455,14 @@ class Blowfish extends BlockCipher
$l = $in[1]; $l = $in[1];
$r = $in[2]; $r = $in[2];
for ($i = 17; $i > 2; $i-= 2) { for ($i = 17; $i > 2; $i -= 2) {
$l^= $p[$i]; $l ^= $p[$i];
$r^= self::safe_intval((self::safe_intval($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]) ^ $r ^= self::safe_intval((self::safe_intval($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]) ^
$sb_2[$l >> 8 & 0xff]) + $sb_2[$l >> 8 & 0xff]) +
$sb_3[$l & 0xff]); $sb_3[$l & 0xff]);
$r^= $p[$i - 1]; $r ^= $p[$i - 1];
$l^= self::safe_intval((self::safe_intval($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]) ^ $l ^= self::safe_intval((self::safe_intval($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]) ^
$sb_2[$r >> 8 & 0xff]) + $sb_2[$r >> 8 & 0xff]) +
$sb_3[$r & 0xff]); $sb_3[$r & 0xff]);
} }
@ -496,8 +496,8 @@ class Blowfish extends BlockCipher
$l = $in[1]; $l = $in[1];
$r = $in[2]; $r = $in[2];
'; ';
for ($i = 0; $i < 16; $i+= 2) { for ($i = 0; $i < 16; $i += 2) {
$encrypt_block.= ' $encrypt_block .= '
$l^= ' . $p[$i] . '; $l^= ' . $p[$i] . ';
$r^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]') . ' ^ $r^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]') . ' ^
$sb_2[$l >> 8 & 0xff]) + $sb_2[$l >> 8 & 0xff]) +
@ -509,7 +509,7 @@ class Blowfish extends BlockCipher
$sb_3[$r & 0xff]') . '; $sb_3[$r & 0xff]') . ';
'; ';
} }
$encrypt_block.= ' $encrypt_block .= '
$in = pack("N*", $in = pack("N*",
$r ^ ' . $p[17] . ', $r ^ ' . $p[17] . ',
$l ^ ' . $p[16] . ' $l ^ ' . $p[16] . '
@ -522,8 +522,8 @@ class Blowfish extends BlockCipher
$r = $in[2]; $r = $in[2];
'; ';
for ($i = 17; $i > 2; $i-= 2) { for ($i = 17; $i > 2; $i -= 2) {
$decrypt_block.= ' $decrypt_block .= '
$l^= ' . $p[$i] . '; $l^= ' . $p[$i] . ';
$r^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]') . ' ^ $r^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]') . ' ^
$sb_2[$l >> 8 & 0xff]) + $sb_2[$l >> 8 & 0xff]) +
@ -536,7 +536,7 @@ class Blowfish extends BlockCipher
'; ';
} }
$decrypt_block.= ' $decrypt_block .= '
$in = pack("N*", $in = pack("N*",
$r ^ ' . $p[0] . ', $r ^ ' . $p[0] . ',
$l ^ ' . $p[1] . ' $l ^ ' . $p[1] . '

View File

@ -258,7 +258,7 @@ class ChaCha20 extends Salsa20
$key = $this->key; $key = $this->key;
if (strlen($key) == 16) { if (strlen($key) == 16) {
$constant = 'expand 16-byte k'; $constant = 'expand 16-byte k';
$key.= $key; $key .= $key;
} else { } else {
$constant = 'expand 32-byte k'; $constant = 'expand 32-byte k';
} }
@ -280,10 +280,15 @@ class ChaCha20 extends Salsa20
*/ */
protected static function quarterRound(&$a, &$b, &$c, &$d) protected static function quarterRound(&$a, &$b, &$c, &$d)
{ {
// in https://datatracker.ietf.org/doc/html/rfc7539#section-2.1 the addition,
// xor'ing and rotation are all on the same line so i'm keeping it on the same
// line here as well
// @codingStandardsIgnoreStart
$a+= $b; $d = self::leftRotate($d ^ $a, 16); $a+= $b; $d = self::leftRotate($d ^ $a, 16);
$c+= $d; $b = self::leftRotate($b ^ $c, 12); $c+= $d; $b = self::leftRotate($b ^ $c, 12);
$a+= $b; $d = self::leftRotate($d ^ $a, 8); $a+= $b; $d = self::leftRotate($d ^ $a, 8);
$c+= $d; $b = self::leftRotate($b ^ $c, 7); $c+= $d; $b = self::leftRotate($b ^ $c, 7);
// @codingStandardsIgnoreEnd
} }
/** /**
@ -355,6 +360,7 @@ class ChaCha20 extends Salsa20
$z14 = $x14; $z14 = $x14;
$z15 = $x15; $z15 = $x15;
// @codingStandardsIgnoreStart
// columnRound // columnRound
$x0+= $x4; $x12 = self::leftRotate($x12 ^ $x0, 16); $x0+= $x4; $x12 = self::leftRotate($x12 ^ $x0, 16);
$x8+= $x12; $x4 = self::leftRotate($x4 ^ $x8, 12); $x8+= $x12; $x4 = self::leftRotate($x4 ^ $x8, 12);
@ -774,23 +780,24 @@ class ChaCha20 extends Salsa20
$x9+= $x14; $x4 = self::leftRotate($x4 ^ $x9, 12); $x9+= $x14; $x4 = self::leftRotate($x4 ^ $x9, 12);
$x3+= $x4; $x14 = self::leftRotate($x14 ^ $x3, 8); $x3+= $x4; $x14 = self::leftRotate($x14 ^ $x3, 8);
$x9+= $x14; $x4 = self::leftRotate($x4 ^ $x9, 7); $x9+= $x14; $x4 = self::leftRotate($x4 ^ $x9, 7);
// @codingStandardsIgnoreEnd
$x0+= $z0; $x0 += $z0;
$x1+= $z1; $x1 += $z1;
$x2+= $z2; $x2 += $z2;
$x3+= $z3; $x3 += $z3;
$x4+= $z4; $x4 += $z4;
$x5+= $z5; $x5 += $z5;
$x6+= $z6; $x6 += $z6;
$x7+= $z7; $x7 += $z7;
$x8+= $z8; $x8 += $z8;
$x9+= $z9; $x9 += $z9;
$x10+= $z10; $x10 += $z10;
$x11+= $z11; $x11 += $z11;
$x12+= $z12; $x12 += $z12;
$x13+= $z13; $x13 += $z13;
$x14+= $z14; $x14 += $z14;
$x15+= $z15; $x15 += $z15;
return pack('V*', $x0, $x1, $x2, $x3, $x4, $x5, $x6, $x7, $x8, $x9, $x10, $x11, $x12, $x13, $x14, $x15); return pack('V*', $x0, $x1, $x2, $x3, $x4, $x5, $x6, $x7, $x8, $x9, $x10, $x11, $x12, $x13, $x14, $x15);
} }

View File

@ -145,7 +145,7 @@ abstract class AsymmetricKey
protected static function initialize_static_variables() protected static function initialize_static_variables()
{ {
if (!isset(self::$zero)) { if (!isset(self::$zero)) {
self::$zero= new BigInteger(0); self::$zero = new BigInteger(0);
self::$one = new BigInteger(1); self::$one = new BigInteger(1);
} }
@ -337,7 +337,7 @@ abstract class AsymmetricKey
* @param string $method optional * @param string $method optional
* @return mixed * @return mixed
*/ */
protected static function validatePlugin($format, $type, $method = NULL) protected static function validatePlugin($format, $type, $method = null)
{ {
$type = strtolower($type); $type = strtolower($type);
if (!isset(self::$plugins[static::ALGORITHM][$format][$type])) { if (!isset(self::$plugins[static::ALGORITHM][$format][$type])) {
@ -581,7 +581,7 @@ abstract class AsymmetricKey
$rolen = $this->q->getLengthInBytes(); $rolen = $this->q->getLengthInBytes();
if (strlen($out) < $rolen) { if (strlen($out) < $rolen) {
return str_pad($out, $rolen, "\0", STR_PAD_LEFT); return str_pad($out, $rolen, "\0", STR_PAD_LEFT);
} else if (strlen($out) > $rolen) { } elseif (strlen($out) > $rolen) {
return substr($out, -$rolen); return substr($out, -$rolen);
} else { } else {
return $out; return $out;

View File

@ -222,7 +222,7 @@ abstract class OpenSSH
*/ */
$paddingLength = (7 * strlen($paddedKey)) % 8; $paddingLength = (7 * strlen($paddedKey)) % 8;
for ($i = 1; $i <= $paddingLength; $i++) { for ($i = 1; $i <= $paddingLength; $i++) {
$paddedKey.= chr($i); $paddedKey .= chr($i);
} }
$key = Strings::packSSH2('sssNss', 'none', 'none', '', 1, $publicKey, $paddedKey); $key = Strings::packSSH2('sssNss', 'none', 'none', '', 1, $publicKey, $paddedKey);
$key = "openssh-key-v1\0$key"; $key = "openssh-key-v1\0$key";

View File

@ -113,7 +113,7 @@ abstract class PKCS1 extends PKCS
$symkey = ''; $symkey = '';
$iv = substr($iv, 0, 8); $iv = substr($iv, 0, 8);
while (strlen($symkey) < $length) { while (strlen($symkey) < $length) {
$symkey.= md5($symkey . $password . $iv, true); $symkey .= md5($symkey . $password . $iv, true);
} }
return substr($symkey, 0, $length); return substr($symkey, 0, $length);
} }
@ -200,7 +200,7 @@ abstract class PKCS1 extends PKCS
$iv = strtoupper(Hex::encode($iv)); $iv = strtoupper(Hex::encode($iv));
return "-----BEGIN $type PRIVATE KEY-----\r\n" . return "-----BEGIN $type PRIVATE KEY-----\r\n" .
"Proc-Type: 4,ENCRYPTED\r\n" . "Proc-Type: 4,ENCRYPTED\r\n" .
"DEK-Info: " . $encryptionAlgorithm. ",$iv\r\n" . "DEK-Info: " . $encryptionAlgorithm . ",$iv\r\n" .
"\r\n" . "\r\n" .
chunk_split(Base64::encode($cipher->encrypt($key)), 64) . chunk_split(Base64::encode($cipher->encrypt($key)), 64) .
"-----END $type PRIVATE KEY-----"; "-----END $type PRIVATE KEY-----";

View File

@ -275,8 +275,7 @@ abstract class PKCS8 extends PKCS
if (!static::$childOIDsLoaded) { if (!static::$childOIDsLoaded) {
ASN1::loadOIDs(is_array(static::OID_NAME) ? ASN1::loadOIDs(is_array(static::OID_NAME) ?
array_combine(static::OID_NAME, static::OID_VALUE) : array_combine(static::OID_NAME, static::OID_VALUE) :
[static::OID_NAME => static::OID_VALUE] [static::OID_NAME => static::OID_VALUE]);
);
static::$childOIDsLoaded = true; static::$childOIDsLoaded = true;
} }
if (!self::$oidsLoaded) { if (!self::$oidsLoaded) {
@ -287,8 +286,8 @@ abstract class PKCS8 extends PKCS
'pbeWithMD2AndRC2-CBC' => '1.2.840.113549.1.5.4', 'pbeWithMD2AndRC2-CBC' => '1.2.840.113549.1.5.4',
'pbeWithMD5AndDES-CBC' => '1.2.840.113549.1.5.3', 'pbeWithMD5AndDES-CBC' => '1.2.840.113549.1.5.3',
'pbeWithMD5AndRC2-CBC' => '1.2.840.113549.1.5.6', 'pbeWithMD5AndRC2-CBC' => '1.2.840.113549.1.5.6',
'pbeWithSHA1AndDES-CBC'=> '1.2.840.113549.1.5.10', 'pbeWithSHA1AndDES-CBC' => '1.2.840.113549.1.5.10',
'pbeWithSHA1AndRC2-CBC'=> '1.2.840.113549.1.5.11', 'pbeWithSHA1AndRC2-CBC' => '1.2.840.113549.1.5.11',
// from PKCS#12: // from PKCS#12:
// https://tools.ietf.org/html/rfc7292 // https://tools.ietf.org/html/rfc7292
@ -308,10 +307,10 @@ abstract class PKCS8 extends PKCS
'id-hmacWithSHA1' => '1.2.840.113549.2.7', 'id-hmacWithSHA1' => '1.2.840.113549.2.7',
'id-hmacWithSHA224' => '1.2.840.113549.2.8', 'id-hmacWithSHA224' => '1.2.840.113549.2.8',
'id-hmacWithSHA256' => '1.2.840.113549.2.9', 'id-hmacWithSHA256' => '1.2.840.113549.2.9',
'id-hmacWithSHA384'=> '1.2.840.113549.2.10', 'id-hmacWithSHA384' => '1.2.840.113549.2.10',
'id-hmacWithSHA512'=> '1.2.840.113549.2.11', 'id-hmacWithSHA512' => '1.2.840.113549.2.11',
'id-hmacWithSHA512-224'=> '1.2.840.113549.2.12', 'id-hmacWithSHA512-224' => '1.2.840.113549.2.12',
'id-hmacWithSHA512-256'=> '1.2.840.113549.2.13', 'id-hmacWithSHA512-256' => '1.2.840.113549.2.13',
'desCBC' => '1.3.14.3.2.7', 'desCBC' => '1.3.14.3.2.7',
'des-EDE3-CBC' => '1.2.840.113549.3.7', 'des-EDE3-CBC' => '1.2.840.113549.3.7',
@ -319,8 +318,8 @@ abstract class PKCS8 extends PKCS
'rc5-CBC-PAD' => '1.2.840.113549.3.9', 'rc5-CBC-PAD' => '1.2.840.113549.3.9',
'aes128-CBC-PAD' => '2.16.840.1.101.3.4.1.2', 'aes128-CBC-PAD' => '2.16.840.1.101.3.4.1.2',
'aes192-CBC-PAD'=> '2.16.840.1.101.3.4.1.22', 'aes192-CBC-PAD' => '2.16.840.1.101.3.4.1.22',
'aes256-CBC-PAD'=> '2.16.840.1.101.3.4.1.42' 'aes256-CBC-PAD' => '2.16.840.1.101.3.4.1.42'
]); ]);
self::$oidsLoaded = true; self::$oidsLoaded = true;
} }

View File

@ -89,7 +89,7 @@ abstract class PuTTY
$sequence = 0; $sequence = 0;
while (strlen($symkey) < $length) { while (strlen($symkey) < $length) {
$temp = pack('Na*', $sequence++, $password); $temp = pack('Na*', $sequence++, $password);
$symkey.= Hex::decode(sha1($temp)); $symkey .= Hex::decode(sha1($temp));
} }
return substr($symkey, 0, $length); return substr($symkey, 0, $length);
} }
@ -170,10 +170,10 @@ abstract class PuTTY
break; break;
case $in_value: case $in_value:
$in_value = $line[strlen($line) - 1] == '\\'; $in_value = $line[strlen($line) - 1] == '\\';
$values[$current].= $in_value ? substr($line, 0, -1) : $line; $values[$current] .= $in_value ? substr($line, 0, -1) : $line;
break; break;
default: default:
$data.= $line; $data .= $line;
} }
} }
@ -181,7 +181,7 @@ abstract class PuTTY
if ($components === false) { if ($components === false) {
throw new \UnexpectedValueException('Unable to decode public key'); throw new \UnexpectedValueException('Unable to decode public key');
} }
$components+= $values; $components += $values;
$components['comment'] = str_replace(['\\\\', '\"'], ['\\', '"'], $values['comment']); $components['comment'] = str_replace(['\\\\', '\"'], ['\\', '"'], $values['comment']);
return $components; return $components;
@ -246,7 +246,7 @@ abstract class PuTTY
case 2: case 2:
$symkey = self::generateV2Key($password, 32); $symkey = self::generateV2Key($password, 32);
$symiv = str_repeat("\0", $crypto->getBlockLength() >> 3); $symiv = str_repeat("\0", $crypto->getBlockLength() >> 3);
$hashkey.= $password; $hashkey .= $password;
} }
} }
@ -270,7 +270,7 @@ abstract class PuTTY
$private = $crypto->decrypt($private); $private = $crypto->decrypt($private);
} }
$source.= Strings::packSSH2('s', $private); $source .= Strings::packSSH2('s', $private);
$hmac = trim(preg_replace('#Private-MAC: (.+)#', '$1', $key[$offset + $privateLength])); $hmac = trim(preg_replace('#Private-MAC: (.+)#', '$1', $key[$offset + $privateLength]));
$hmac = Hex::decode($hmac); $hmac = Hex::decode($hmac);
@ -302,19 +302,19 @@ abstract class PuTTY
$version = isset($options['version']) ? $options['version'] : self::$version; $version = isset($options['version']) ? $options['version'] : self::$version;
$key = "PuTTY-User-Key-File-$version: $type\r\n"; $key = "PuTTY-User-Key-File-$version: $type\r\n";
$key.= "Encryption: $encryption\r\n"; $key .= "Encryption: $encryption\r\n";
$key.= "Comment: $comment\r\n"; $key .= "Comment: $comment\r\n";
$public = Strings::packSSH2('s', $type) . $public; $public = Strings::packSSH2('s', $type) . $public;
$source = Strings::packSSH2('ssss', $type, $encryption, $comment, $public); $source = Strings::packSSH2('ssss', $type, $encryption, $comment, $public);
$public = Base64::encode($public); $public = Base64::encode($public);
$key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n"; $key .= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n";
$key.= chunk_split($public, 64); $key .= chunk_split($public, 64);
if (empty($password) && !is_string($password)) { if (empty($password) && !is_string($password)) {
$source.= Strings::packSSH2('s', $private); $source .= Strings::packSSH2('s', $private);
switch ($version) { switch ($version) {
case 3: case 3:
$hash = new Hash('sha256'); $hash = new Hash('sha256');
@ -325,18 +325,18 @@ abstract class PuTTY
$hash->setKey(sha1('putty-private-key-file-mac-key', true)); $hash->setKey(sha1('putty-private-key-file-mac-key', true));
} }
} else { } else {
$private.= Random::string(16 - (strlen($private) & 15)); $private .= Random::string(16 - (strlen($private) & 15));
$source.= Strings::packSSH2('s', $private); $source .= Strings::packSSH2('s', $private);
$crypto = new AES('cbc'); $crypto = new AES('cbc');
switch ($version) { switch ($version) {
case 3: case 3:
$salt = Random::string(16); $salt = Random::string(16);
$key.= "Key-Derivation: Argon2id\r\n"; $key .= "Key-Derivation: Argon2id\r\n";
$key.= "Argon2-Memory: 8192\r\n"; $key .= "Argon2-Memory: 8192\r\n";
$key.= "Argon2-Passes: 13\r\n"; $key .= "Argon2-Passes: 13\r\n";
$key.= "Argon2-Parallelism: 1\r\n"; $key .= "Argon2-Parallelism: 1\r\n";
$key.= "Argon2-Salt: " . Hex::encode($salt) . "\r\n"; $key .= "Argon2-Salt: " . Hex::encode($salt) . "\r\n";
extract(self::generateV3Key($password, 'Argon2id', 8192, 13, $salt)); extract(self::generateV3Key($password, 'Argon2id', 8192, 13, $salt));
$hash = new Hash('sha256'); $hash = new Hash('sha256');
@ -360,9 +360,9 @@ abstract class PuTTY
} }
$private = Base64::encode($private); $private = Base64::encode($private);
$key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n"; $key .= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n";
$key.= chunk_split($private, 64); $key .= chunk_split($private, 64);
$key.= 'Private-MAC: ' . Hex::encode($hash->hash($source)) . "\r\n"; $key .= 'Private-MAC: ' . Hex::encode($hash->hash($source)) . "\r\n";
return $key; return $key;
} }

View File

@ -887,7 +887,7 @@ abstract class SymmetricKey
if (is_string($this->key) && strlen($this->key) != $this->explicit_key_length) { if (is_string($this->key) && strlen($this->key) != $this->explicit_key_length) {
$this->key = false; $this->key = false;
throw new InconsistentSetupException('Key has already been set and is not ' .$this->explicit_key_length . ' bytes long'); throw new InconsistentSetupException('Key has already been set and is not ' . $this->explicit_key_length . ' bytes long');
} }
} }
@ -980,7 +980,7 @@ abstract class SymmetricKey
-- https://tools.ietf.org/html/rfc7292#appendix-B.1 -- https://tools.ietf.org/html/rfc7292#appendix-B.1
*/ */
$password = "\0". chunk_split($password, 1, "\0") . "\0"; $password = "\0" . chunk_split($password, 1, "\0") . "\0";
/* /*
This standard specifies 3 different values for the ID byte mentioned This standard specifies 3 different values for the ID byte mentioned
@ -1003,7 +1003,7 @@ abstract class SymmetricKey
$s = ''; $s = '';
if (strlen($salt)) { if (strlen($salt)) {
while (strlen($s) < $blockLength) { while (strlen($s) < $blockLength) {
$s.= $salt; $s .= $salt;
} }
} }
$s = substr($s, 0, $blockLength); $s = substr($s, 0, $blockLength);
@ -1011,7 +1011,7 @@ abstract class SymmetricKey
$p = ''; $p = '';
if (strlen($password)) { if (strlen($password)) {
while (strlen($p) < $blockLength) { while (strlen($p) < $blockLength) {
$p.= $password; $p .= $password;
} }
} }
$p = substr($p, 0, $blockLength); $p = substr($p, 0, $blockLength);
@ -1047,9 +1047,9 @@ abstract class SymmetricKey
$f = $u = $hashObj->hash($salt . pack('N', $i++)); $f = $u = $hashObj->hash($salt . pack('N', $i++));
for ($j = 2; $j <= $count; ++$j) { for ($j = 2; $j <= $count; ++$j) {
$u = $hashObj->hash($u); $u = $hashObj->hash($u);
$f^= $u; $f ^= $u;
} }
$key.= $f; $key .= $f;
} }
$key = substr($key, 0, $dkLen); $key = substr($key, 0, $dkLen);
break; break;
@ -1100,21 +1100,21 @@ abstract class SymmetricKey
} }
$b = ''; $b = '';
while (strlen($b) < $blockLength) { while (strlen($b) < $blockLength) {
$b.= $ai; $b .= $ai;
} }
$b = substr($b, 0, $blockLength); $b = substr($b, 0, $blockLength);
$b = new BigInteger($b, 256); $b = new BigInteger($b, 256);
$newi = ''; $newi = '';
for ($k = 0; $k < strlen($i); $k+= $blockLength) { for ($k = 0; $k < strlen($i); $k += $blockLength) {
$temp = substr($i, $k, $blockLength); $temp = substr($i, $k, $blockLength);
$temp = new BigInteger($temp, 256); $temp = new BigInteger($temp, 256);
$temp->setPrecision($blockLength << 3); $temp->setPrecision($blockLength << 3);
$temp = $temp->add($b); $temp = $temp->add($b);
$temp = $temp->add($one); $temp = $temp->add($one);
$newi.= $temp->toBytes(false); $newi .= $temp->toBytes(false);
} }
$i = $newi; $i = $newi;
$a.= $ai; $a .= $ai;
} }
return substr($a, 0, $n); return substr($a, 0, $n);
@ -1209,11 +1209,11 @@ abstract class SymmetricKey
$max = $this->block_size - $pos; $max = $this->block_size - $pos;
if ($len >= $max) { if ($len >= $max) {
$i = $max; $i = $max;
$len-= $max; $len -= $max;
$pos = 0; $pos = 0;
} else { } else {
$i = $len; $i = $len;
$pos+= $len; $pos += $len;
$len = 0; $len = 0;
} }
// ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
@ -1225,13 +1225,13 @@ abstract class SymmetricKey
$overflow = $len % $this->block_size; $overflow = $len % $this->block_size;
if ($overflow) { if ($overflow) {
$ciphertext.= openssl_encrypt(substr($plaintext, 0, -$overflow) . str_repeat("\0", $this->block_size), $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); $ciphertext .= openssl_encrypt(substr($plaintext, 0, -$overflow) . str_repeat("\0", $this->block_size), $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
$iv = Strings::pop($ciphertext, $this->block_size); $iv = Strings::pop($ciphertext, $this->block_size);
$size = $len - $overflow; $size = $len - $overflow;
$block = $iv ^ substr($plaintext, -$overflow); $block = $iv ^ substr($plaintext, -$overflow);
$iv = substr_replace($iv, $block, 0, $overflow); $iv = substr_replace($iv, $block, 0, $overflow);
$ciphertext.= $block; $ciphertext .= $block;
$pos = $overflow; $pos = $overflow;
} elseif ($len) { } elseif ($len) {
$ciphertext = openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); $ciphertext = openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
@ -1256,7 +1256,7 @@ abstract class SymmetricKey
for ($i = 0; $i < $len; ++$i) { for ($i = 0; $i < $len; ++$i) {
$xor = openssl_encrypt($iv, $this->cipher_name_openssl_ecb, $this->key, $this->openssl_options, $this->decryptIV); $xor = openssl_encrypt($iv, $this->cipher_name_openssl_ecb, $this->key, $this->openssl_options, $this->decryptIV);
$ciphertext.= $plaintext[$i] ^ $xor; $ciphertext .= $plaintext[$i] ^ $xor;
$iv = substr($iv, 1) . $xor[0]; $iv = substr($iv, 1) . $xor[0];
} }
@ -1270,7 +1270,8 @@ abstract class SymmetricKey
} }
if ($this->engine === self::ENGINE_MCRYPT) { if ($this->engine === self::ENGINE_MCRYPT) {
set_error_handler(function() {}); set_error_handler(function () {
});
if ($this->enchanged) { if ($this->enchanged) {
mcrypt_generic_init($this->enmcrypt, $this->key, $this->getIV($this->encryptIV)); mcrypt_generic_init($this->enmcrypt, $this->key, $this->getIV($this->encryptIV));
$this->enchanged = false; $this->enchanged = false;
@ -1291,11 +1292,11 @@ abstract class SymmetricKey
$max = $block_size - $pos; $max = $block_size - $pos;
if ($len >= $max) { if ($len >= $max) {
$i = $max; $i = $max;
$len-= $max; $len -= $max;
$pos = 0; $pos = 0;
} else { } else {
$i = $len; $i = $len;
$pos+= $len; $pos += $len;
$len = 0; $len = 0;
} }
$ciphertext = substr($iv, $orig_pos) ^ $plaintext; $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
@ -1308,15 +1309,15 @@ abstract class SymmetricKey
mcrypt_generic_init($this->enmcrypt, $this->key, $iv); mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
$this->enbuffer['enmcrypt_init'] = false; $this->enbuffer['enmcrypt_init'] = false;
} }
$ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size)); $ciphertext .= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
$iv = substr($ciphertext, -$block_size); $iv = substr($ciphertext, -$block_size);
$len%= $block_size; $len %= $block_size;
} else { } else {
while ($len >= $block_size) { while ($len >= $block_size) {
$iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size); $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
$ciphertext.= $iv; $ciphertext .= $iv;
$len-= $block_size; $len -= $block_size;
$i+= $block_size; $i += $block_size;
} }
} }
} }
@ -1325,7 +1326,7 @@ abstract class SymmetricKey
$iv = mcrypt_generic($this->ecb, $iv); $iv = mcrypt_generic($this->ecb, $iv);
$block = $iv ^ substr($plaintext, -$len); $block = $iv ^ substr($plaintext, -$len);
$iv = substr_replace($iv, $block, 0, $len); $iv = substr_replace($iv, $block, 0, $len);
$ciphertext.= $block; $ciphertext .= $block;
$pos = $len; $pos = $len;
} }
@ -1355,17 +1356,17 @@ abstract class SymmetricKey
$ciphertext = ''; $ciphertext = '';
switch ($this->mode) { switch ($this->mode) {
case self::MODE_ECB: case self::MODE_ECB:
for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { for ($i = 0; $i < strlen($plaintext); $i += $block_size) {
$ciphertext.= $this->encryptBlock(substr($plaintext, $i, $block_size)); $ciphertext .= $this->encryptBlock(substr($plaintext, $i, $block_size));
} }
break; break;
case self::MODE_CBC: case self::MODE_CBC:
$xor = $this->encryptIV; $xor = $this->encryptIV;
for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { for ($i = 0; $i < strlen($plaintext); $i += $block_size) {
$block = substr($plaintext, $i, $block_size); $block = substr($plaintext, $i, $block_size);
$block = $this->encryptBlock($block ^ $xor); $block = $this->encryptBlock($block ^ $xor);
$xor = $block; $xor = $block;
$ciphertext.= $block; $ciphertext .= $block;
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$this->encryptIV = $xor; $this->encryptIV = $xor;
@ -1374,21 +1375,21 @@ abstract class SymmetricKey
case self::MODE_CTR: case self::MODE_CTR:
$xor = $this->encryptIV; $xor = $this->encryptIV;
if (strlen($buffer['ciphertext'])) { if (strlen($buffer['ciphertext'])) {
for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { for ($i = 0; $i < strlen($plaintext); $i += $block_size) {
$block = substr($plaintext, $i, $block_size); $block = substr($plaintext, $i, $block_size);
if (strlen($block) > strlen($buffer['ciphertext'])) { if (strlen($block) > strlen($buffer['ciphertext'])) {
$buffer['ciphertext'].= $this->encryptBlock($xor); $buffer['ciphertext'] .= $this->encryptBlock($xor);
Strings::increment_str($xor); Strings::increment_str($xor);
} }
$key = Strings::shift($buffer['ciphertext'], $block_size); $key = Strings::shift($buffer['ciphertext'], $block_size);
$ciphertext.= $block ^ $key; $ciphertext .= $block ^ $key;
} }
} else { } else {
for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { for ($i = 0; $i < strlen($plaintext); $i += $block_size) {
$block = substr($plaintext, $i, $block_size); $block = substr($plaintext, $i, $block_size);
$key = $this->encryptBlock($xor); $key = $this->encryptBlock($xor);
Strings::increment_str($xor); Strings::increment_str($xor);
$ciphertext.= $block ^ $key; $ciphertext .= $block ^ $key;
} }
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
@ -1415,11 +1416,11 @@ abstract class SymmetricKey
$max = $block_size - $pos; $max = $block_size - $pos;
if ($len >= $max) { if ($len >= $max) {
$i = $max; $i = $max;
$len-= $max; $len -= $max;
$pos = 0; $pos = 0;
} else { } else {
$i = $len; $i = $len;
$pos+= $len; $pos += $len;
$len = 0; $len = 0;
} }
// ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
@ -1428,15 +1429,15 @@ abstract class SymmetricKey
} }
while ($len >= $block_size) { while ($len >= $block_size) {
$iv = $this->encryptBlock($iv) ^ substr($plaintext, $i, $block_size); $iv = $this->encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
$ciphertext.= $iv; $ciphertext .= $iv;
$len-= $block_size; $len -= $block_size;
$i+= $block_size; $i += $block_size;
} }
if ($len) { if ($len) {
$iv = $this->encryptBlock($iv); $iv = $this->encryptBlock($iv);
$block = $iv ^ substr($plaintext, $i); $block = $iv ^ substr($plaintext, $i);
$iv = substr_replace($iv, $block, 0, $len); $iv = substr_replace($iv, $block, 0, $len);
$ciphertext.= $block; $ciphertext .= $block;
$pos = $len; $pos = $len;
} }
break; break;
@ -1465,7 +1466,7 @@ abstract class SymmetricKey
for ($i = 0; $i < $len; ++$i) { for ($i = 0; $i < $len; ++$i) {
$xor = $this->encryptBlock($iv); $xor = $this->encryptBlock($iv);
$ciphertext.= $plaintext[$i] ^ $xor; $ciphertext .= $plaintext[$i] ^ $xor;
$iv = substr($iv, 1) . $xor[0]; $iv = substr($iv, 1) . $xor[0];
} }
@ -1476,19 +1477,19 @@ abstract class SymmetricKey
case self::MODE_OFB: case self::MODE_OFB:
$xor = $this->encryptIV; $xor = $this->encryptIV;
if (strlen($buffer['xor'])) { if (strlen($buffer['xor'])) {
for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { for ($i = 0; $i < strlen($plaintext); $i += $block_size) {
$block = substr($plaintext, $i, $block_size); $block = substr($plaintext, $i, $block_size);
if (strlen($block) > strlen($buffer['xor'])) { if (strlen($block) > strlen($buffer['xor'])) {
$xor = $this->encryptBlock($xor); $xor = $this->encryptBlock($xor);
$buffer['xor'].= $xor; $buffer['xor'] .= $xor;
} }
$key = Strings::shift($buffer['xor'], $block_size); $key = Strings::shift($buffer['xor'], $block_size);
$ciphertext.= $block ^ $key; $ciphertext .= $block ^ $key;
} }
} else { } else {
for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { for ($i = 0; $i < strlen($plaintext); $i += $block_size) {
$xor = $this->encryptBlock($xor); $xor = $this->encryptBlock($xor);
$ciphertext.= substr($plaintext, $i, $block_size) ^ $xor; $ciphertext .= substr($plaintext, $i, $block_size) ^ $xor;
} }
$key = $xor; $key = $xor;
} }
@ -1600,11 +1601,11 @@ abstract class SymmetricKey
$max = $this->block_size - $pos; $max = $this->block_size - $pos;
if ($len >= $max) { if ($len >= $max) {
$i = $max; $i = $max;
$len-= $max; $len -= $max;
$pos = 0; $pos = 0;
} else { } else {
$i = $len; $i = $len;
$pos+= $len; $pos += $len;
$len = 0; $len = 0;
} }
// ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $this->blocksize // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $this->blocksize
@ -1614,16 +1615,16 @@ abstract class SymmetricKey
} }
$overflow = $len % $this->block_size; $overflow = $len % $this->block_size;
if ($overflow) { if ($overflow) {
$plaintext.= openssl_decrypt(substr($ciphertext, 0, -$overflow), $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); $plaintext .= openssl_decrypt(substr($ciphertext, 0, -$overflow), $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
if ($len - $overflow) { if ($len - $overflow) {
$iv = substr($ciphertext, -$overflow - $this->block_size, -$overflow); $iv = substr($ciphertext, -$overflow - $this->block_size, -$overflow);
} }
$iv = openssl_encrypt(str_repeat("\0", $this->block_size), $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); $iv = openssl_encrypt(str_repeat("\0", $this->block_size), $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
$plaintext.= $iv ^ substr($ciphertext, -$overflow); $plaintext .= $iv ^ substr($ciphertext, -$overflow);
$iv = substr_replace($iv, substr($ciphertext, -$overflow), 0, $overflow); $iv = substr_replace($iv, substr($ciphertext, -$overflow), 0, $overflow);
$pos = $overflow; $pos = $overflow;
} elseif ($len) { } elseif ($len) {
$plaintext.= openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); $plaintext .= openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
$iv = substr($ciphertext, -$this->block_size); $iv = substr($ciphertext, -$this->block_size);
} }
break; break;
@ -1644,7 +1645,7 @@ abstract class SymmetricKey
for ($i = 0; $i < $len; ++$i) { for ($i = 0; $i < $len; ++$i) {
$xor = openssl_encrypt($iv, $this->cipher_name_openssl_ecb, $this->key, $this->openssl_options, $this->decryptIV); $xor = openssl_encrypt($iv, $this->cipher_name_openssl_ecb, $this->key, $this->openssl_options, $this->decryptIV);
$plaintext.= $ciphertext[$i] ^ $xor; $plaintext .= $ciphertext[$i] ^ $xor;
$iv = substr($iv, 1) . $xor[0]; $iv = substr($iv, 1) . $xor[0];
} }
@ -1660,7 +1661,8 @@ abstract class SymmetricKey
} }
if ($this->engine === self::ENGINE_MCRYPT) { if ($this->engine === self::ENGINE_MCRYPT) {
set_error_handler(function() {}); set_error_handler(function () {
});
$block_size = $this->block_size; $block_size = $this->block_size;
if ($this->dechanged) { if ($this->dechanged) {
mcrypt_generic_init($this->demcrypt, $this->key, $this->getIV($this->decryptIV)); mcrypt_generic_init($this->demcrypt, $this->key, $this->getIV($this->decryptIV));
@ -1678,11 +1680,11 @@ abstract class SymmetricKey
$max = $block_size - $pos; $max = $block_size - $pos;
if ($len >= $max) { if ($len >= $max) {
$i = $max; $i = $max;
$len-= $max; $len -= $max;
$pos = 0; $pos = 0;
} else { } else {
$i = $len; $i = $len;
$pos+= $len; $pos += $len;
$len = 0; $len = 0;
} }
// ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
@ -1691,13 +1693,13 @@ abstract class SymmetricKey
} }
if ($len >= $block_size) { if ($len >= $block_size) {
$cb = substr($ciphertext, $i, $len - $len % $block_size); $cb = substr($ciphertext, $i, $len - $len % $block_size);
$plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb; $plaintext .= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
$iv = substr($cb, -$block_size); $iv = substr($cb, -$block_size);
$len%= $block_size; $len %= $block_size;
} }
if ($len) { if ($len) {
$iv = mcrypt_generic($this->ecb, $iv); $iv = mcrypt_generic($this->ecb, $iv);
$plaintext.= $iv ^ substr($ciphertext, -$len); $plaintext .= $iv ^ substr($ciphertext, -$len);
$iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len); $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
$pos = $len; $pos = $len;
} }
@ -1729,15 +1731,15 @@ abstract class SymmetricKey
$plaintext = ''; $plaintext = '';
switch ($this->mode) { switch ($this->mode) {
case self::MODE_ECB: case self::MODE_ECB:
for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { for ($i = 0; $i < strlen($ciphertext); $i += $block_size) {
$plaintext.= $this->decryptBlock(substr($ciphertext, $i, $block_size)); $plaintext .= $this->decryptBlock(substr($ciphertext, $i, $block_size));
} }
break; break;
case self::MODE_CBC: case self::MODE_CBC:
$xor = $this->decryptIV; $xor = $this->decryptIV;
for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { for ($i = 0; $i < strlen($ciphertext); $i += $block_size) {
$block = substr($ciphertext, $i, $block_size); $block = substr($ciphertext, $i, $block_size);
$plaintext.= $this->decryptBlock($block) ^ $xor; $plaintext .= $this->decryptBlock($block) ^ $xor;
$xor = $block; $xor = $block;
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
@ -1747,21 +1749,21 @@ abstract class SymmetricKey
case self::MODE_CTR: case self::MODE_CTR:
$xor = $this->decryptIV; $xor = $this->decryptIV;
if (strlen($buffer['ciphertext'])) { if (strlen($buffer['ciphertext'])) {
for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { for ($i = 0; $i < strlen($ciphertext); $i += $block_size) {
$block = substr($ciphertext, $i, $block_size); $block = substr($ciphertext, $i, $block_size);
if (strlen($block) > strlen($buffer['ciphertext'])) { if (strlen($block) > strlen($buffer['ciphertext'])) {
$buffer['ciphertext'].= $this->encryptBlock($xor); $buffer['ciphertext'] .= $this->encryptBlock($xor);
Strings::increment_str($xor); Strings::increment_str($xor);
} }
$key = Strings::shift($buffer['ciphertext'], $block_size); $key = Strings::shift($buffer['ciphertext'], $block_size);
$plaintext.= $block ^ $key; $plaintext .= $block ^ $key;
} }
} else { } else {
for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { for ($i = 0; $i < strlen($ciphertext); $i += $block_size) {
$block = substr($ciphertext, $i, $block_size); $block = substr($ciphertext, $i, $block_size);
$key = $this->encryptBlock($xor); $key = $this->encryptBlock($xor);
Strings::increment_str($xor); Strings::increment_str($xor);
$plaintext.= $block ^ $key; $plaintext .= $block ^ $key;
} }
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
@ -1786,11 +1788,11 @@ abstract class SymmetricKey
$max = $block_size - $pos; $max = $block_size - $pos;
if ($len >= $max) { if ($len >= $max) {
$i = $max; $i = $max;
$len-= $max; $len -= $max;
$pos = 0; $pos = 0;
} else { } else {
$i = $len; $i = $len;
$pos+= $len; $pos += $len;
$len = 0; $len = 0;
} }
// ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
@ -1800,14 +1802,14 @@ abstract class SymmetricKey
while ($len >= $block_size) { while ($len >= $block_size) {
$iv = $this->encryptBlock($iv); $iv = $this->encryptBlock($iv);
$cb = substr($ciphertext, $i, $block_size); $cb = substr($ciphertext, $i, $block_size);
$plaintext.= $iv ^ $cb; $plaintext .= $iv ^ $cb;
$iv = $cb; $iv = $cb;
$len-= $block_size; $len -= $block_size;
$i+= $block_size; $i += $block_size;
} }
if ($len) { if ($len) {
$iv = $this->encryptBlock($iv); $iv = $this->encryptBlock($iv);
$plaintext.= $iv ^ substr($ciphertext, $i); $plaintext .= $iv ^ substr($ciphertext, $i);
$iv = substr_replace($iv, substr($ciphertext, $i), 0, $len); $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
$pos = $len; $pos = $len;
} }
@ -1837,7 +1839,7 @@ abstract class SymmetricKey
for ($i = 0; $i < $len; ++$i) { for ($i = 0; $i < $len; ++$i) {
$xor = $this->encryptBlock($iv); $xor = $this->encryptBlock($iv);
$plaintext.= $ciphertext[$i] ^ $xor; $plaintext .= $ciphertext[$i] ^ $xor;
$iv = substr($iv, 1) . $xor[0]; $iv = substr($iv, 1) . $xor[0];
} }
@ -1848,19 +1850,19 @@ abstract class SymmetricKey
case self::MODE_OFB: case self::MODE_OFB:
$xor = $this->decryptIV; $xor = $this->decryptIV;
if (strlen($buffer['xor'])) { if (strlen($buffer['xor'])) {
for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { for ($i = 0; $i < strlen($ciphertext); $i += $block_size) {
$block = substr($ciphertext, $i, $block_size); $block = substr($ciphertext, $i, $block_size);
if (strlen($block) > strlen($buffer['xor'])) { if (strlen($block) > strlen($buffer['xor'])) {
$xor = $this->encryptBlock($xor); $xor = $this->encryptBlock($xor);
$buffer['xor'].= $xor; $buffer['xor'] .= $xor;
} }
$key = Strings::shift($buffer['xor'], $block_size); $key = Strings::shift($buffer['xor'], $block_size);
$plaintext.= $block ^ $key; $plaintext .= $block ^ $key;
} }
} else { } else {
for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { for ($i = 0; $i < strlen($ciphertext); $i += $block_size) {
$xor = $this->encryptBlock($xor); $xor = $this->encryptBlock($xor);
$plaintext.= substr($ciphertext, $i, $block_size) ^ $xor; $plaintext .= substr($ciphertext, $i, $block_size) ^ $xor;
} }
$key = $xor; $key = $xor;
} }
@ -1984,21 +1986,21 @@ abstract class SymmetricKey
if ($this->openssl_emulate_ctr) { if ($this->openssl_emulate_ctr) {
$xor = $encryptIV; $xor = $encryptIV;
if (strlen($buffer['ciphertext'])) { if (strlen($buffer['ciphertext'])) {
for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { for ($i = 0; $i < strlen($plaintext); $i += $block_size) {
$block = substr($plaintext, $i, $block_size); $block = substr($plaintext, $i, $block_size);
if (strlen($block) > strlen($buffer['ciphertext'])) { if (strlen($block) > strlen($buffer['ciphertext'])) {
$buffer['ciphertext'].= openssl_encrypt($xor, $this->cipher_name_openssl_ecb, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING); $buffer['ciphertext'] .= openssl_encrypt($xor, $this->cipher_name_openssl_ecb, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
} }
Strings::increment_str($xor); Strings::increment_str($xor);
$otp = Strings::shift($buffer['ciphertext'], $block_size); $otp = Strings::shift($buffer['ciphertext'], $block_size);
$ciphertext.= $block ^ $otp; $ciphertext .= $block ^ $otp;
} }
} else { } else {
for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { for ($i = 0; $i < strlen($plaintext); $i += $block_size) {
$block = substr($plaintext, $i, $block_size); $block = substr($plaintext, $i, $block_size);
$otp = openssl_encrypt($xor, $this->cipher_name_openssl_ecb, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING); $otp = openssl_encrypt($xor, $this->cipher_name_openssl_ecb, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
Strings::increment_str($xor); Strings::increment_str($xor);
$ciphertext.= $block ^ $otp; $ciphertext .= $block ^ $otp;
} }
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
@ -2025,13 +2027,13 @@ abstract class SymmetricKey
$plaintext2 = Strings::pop($plaintext, $overflow); // ie. trim $plaintext to a multiple of $block_size and put rest of $plaintext in $plaintext2 $plaintext2 = Strings::pop($plaintext, $overflow); // ie. trim $plaintext to a multiple of $block_size and put rest of $plaintext in $plaintext2
$encrypted = openssl_encrypt($plaintext . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $encryptIV); $encrypted = openssl_encrypt($plaintext . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $encryptIV);
$temp = Strings::pop($encrypted, $block_size); $temp = Strings::pop($encrypted, $block_size);
$ciphertext.= $encrypted . ($plaintext2 ^ $temp); $ciphertext .= $encrypted . ($plaintext2 ^ $temp);
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$buffer['ciphertext'] = substr($temp, $overflow); $buffer['ciphertext'] = substr($temp, $overflow);
$encryptIV = $temp; $encryptIV = $temp;
} }
} elseif (!strlen($buffer['ciphertext'])) { } elseif (!strlen($buffer['ciphertext'])) {
$ciphertext.= openssl_encrypt($plaintext . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $encryptIV); $ciphertext .= openssl_encrypt($plaintext . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $encryptIV);
$temp = Strings::pop($ciphertext, $block_size); $temp = Strings::pop($ciphertext, $block_size);
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$encryptIV = $temp; $encryptIV = $temp;
@ -2080,12 +2082,12 @@ abstract class SymmetricKey
if (strlen($plaintext)) { if (strlen($plaintext)) {
if ($overflow) { if ($overflow) {
$ciphertext.= openssl_encrypt(substr($plaintext, 0, -$overflow) . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $encryptIV); $ciphertext .= openssl_encrypt(substr($plaintext, 0, -$overflow) . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $encryptIV);
$xor = Strings::pop($ciphertext, $block_size); $xor = Strings::pop($ciphertext, $block_size);
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$encryptIV = $xor; $encryptIV = $xor;
} }
$ciphertext.= Strings::shift($xor, $overflow) ^ substr($plaintext, -$overflow); $ciphertext .= Strings::shift($xor, $overflow) ^ substr($plaintext, -$overflow);
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$buffer['xor'] = $xor; $buffer['xor'] = $xor;
} }
@ -2270,7 +2272,8 @@ abstract class SymmetricKey
} }
return false; return false;
case self::ENGINE_MCRYPT: case self::ENGINE_MCRYPT:
set_error_handler(function() {}); set_error_handler(function () {
});
$result = $this->cipher_name_mcrypt && $result = $this->cipher_name_mcrypt &&
extension_loaded('mcrypt') && extension_loaded('mcrypt') &&
in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()); in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms());
@ -2388,7 +2391,8 @@ abstract class SymmetricKey
} }
if ($this->engine != self::ENGINE_MCRYPT && $this->enmcrypt) { if ($this->engine != self::ENGINE_MCRYPT && $this->enmcrypt) {
set_error_handler(function() {}); set_error_handler(function () {
});
// Closing the current mcrypt resource(s). _mcryptSetup() will, if needed, // Closing the current mcrypt resource(s). _mcryptSetup() will, if needed,
// (re)open them with the module named in $this->cipher_name_mcrypt // (re)open them with the module named in $this->cipher_name_mcrypt
mcrypt_module_close($this->enmcrypt); mcrypt_module_close($this->enmcrypt);
@ -2508,7 +2512,8 @@ abstract class SymmetricKey
case self::ENGINE_MCRYPT: case self::ENGINE_MCRYPT:
$this->enchanged = $this->dechanged = true; $this->enchanged = $this->dechanged = true;
set_error_handler(function() {}); set_error_handler(function () {
});
if (!isset($this->enmcrypt)) { if (!isset($this->enmcrypt)) {
static $mcrypt_modes = [ static $mcrypt_modes = [
@ -2531,7 +2536,6 @@ abstract class SymmetricKey
if ($this->mode == self::MODE_CFB) { if ($this->mode == self::MODE_CFB) {
$this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, ''); $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
} }
} // else should mcrypt_generic_deinit be called? } // else should mcrypt_generic_deinit be called?
if ($this->mode == self::MODE_CFB) { if ($this->mode == self::MODE_CFB) {
@ -2806,9 +2810,9 @@ abstract class SymmetricKey
$_ciphertext = ""; $_ciphertext = "";
$_plaintext_len = strlen($_text); $_plaintext_len = strlen($_text);
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
$in = substr($_text, $_i, '.$block_size.'); $in = substr($_text, $_i, ' . $block_size . ');
'.$encrypt_block.' ' . $encrypt_block . '
$_ciphertext.= $in; $_ciphertext.= $in;
} }
@ -2817,12 +2821,12 @@ abstract class SymmetricKey
$decrypt = $init_decrypt . ' $decrypt = $init_decrypt . '
$_plaintext = ""; $_plaintext = "";
$_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0)); $_text = str_pad($_text, strlen($_text) + (' . $block_size . ' - strlen($_text) % ' . $block_size . ') % ' . $block_size . ', chr(0));
$_ciphertext_len = strlen($_text); $_ciphertext_len = strlen($_text);
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
$in = substr($_text, $_i, '.$block_size.'); $in = substr($_text, $_i, ' . $block_size . ');
'.$decrypt_block.' ' . $decrypt_block . '
$_plaintext.= $in; $_plaintext.= $in;
} }
@ -2836,22 +2840,22 @@ abstract class SymmetricKey
$_xor = $this->encryptIV; $_xor = $this->encryptIV;
$_buffer = &$this->enbuffer; $_buffer = &$this->enbuffer;
if (strlen($_buffer["ciphertext"])) { if (strlen($_buffer["ciphertext"])) {
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
$_block = substr($_text, $_i, '.$block_size.'); $_block = substr($_text, $_i, ' . $block_size . ');
if (strlen($_block) > strlen($_buffer["ciphertext"])) { if (strlen($_block) > strlen($_buffer["ciphertext"])) {
$in = $_xor; $in = $_xor;
'.$encrypt_block.' ' . $encrypt_block . '
\phpseclib3\Common\Functions\Strings::increment_str($_xor); \phpseclib3\Common\Functions\Strings::increment_str($_xor);
$_buffer["ciphertext"].= $in; $_buffer["ciphertext"].= $in;
} }
$_key = \phpseclib3\Common\Functions\Strings::shift($_buffer["ciphertext"], '.$block_size.'); $_key = \phpseclib3\Common\Functions\Strings::shift($_buffer["ciphertext"], ' . $block_size . ');
$_ciphertext.= $_block ^ $_key; $_ciphertext.= $_block ^ $_key;
} }
} else { } else {
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
$_block = substr($_text, $_i, '.$block_size.'); $_block = substr($_text, $_i, ' . $block_size . ');
$in = $_xor; $in = $_xor;
'.$encrypt_block.' ' . $encrypt_block . '
\phpseclib3\Common\Functions\Strings::increment_str($_xor); \phpseclib3\Common\Functions\Strings::increment_str($_xor);
$_key = $in; $_key = $in;
$_ciphertext.= $_block ^ $_key; $_ciphertext.= $_block ^ $_key;
@ -2859,7 +2863,7 @@ abstract class SymmetricKey
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$this->encryptIV = $_xor; $this->encryptIV = $_xor;
if ($_start = $_plaintext_len % '.$block_size.') { if ($_start = $_plaintext_len % ' . $block_size . ') {
$_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"]; $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
} }
} }
@ -2874,22 +2878,22 @@ abstract class SymmetricKey
$_buffer = &$this->debuffer; $_buffer = &$this->debuffer;
if (strlen($_buffer["ciphertext"])) { if (strlen($_buffer["ciphertext"])) {
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
$_block = substr($_text, $_i, '.$block_size.'); $_block = substr($_text, $_i, ' . $block_size . ');
if (strlen($_block) > strlen($_buffer["ciphertext"])) { if (strlen($_block) > strlen($_buffer["ciphertext"])) {
$in = $_xor; $in = $_xor;
'.$encrypt_block.' ' . $encrypt_block . '
\phpseclib3\Common\Functions\Strings::increment_str($_xor); \phpseclib3\Common\Functions\Strings::increment_str($_xor);
$_buffer["ciphertext"].= $in; $_buffer["ciphertext"].= $in;
} }
$_key = \phpseclib3\Common\Functions\Strings::shift($_buffer["ciphertext"], '.$block_size.'); $_key = \phpseclib3\Common\Functions\Strings::shift($_buffer["ciphertext"], ' . $block_size . ');
$_plaintext.= $_block ^ $_key; $_plaintext.= $_block ^ $_key;
} }
} else { } else {
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
$_block = substr($_text, $_i, '.$block_size.'); $_block = substr($_text, $_i, ' . $block_size . ');
$in = $_xor; $in = $_xor;
'.$encrypt_block.' ' . $encrypt_block . '
\phpseclib3\Common\Functions\Strings::increment_str($_xor); \phpseclib3\Common\Functions\Strings::increment_str($_xor);
$_key = $in; $_key = $in;
$_plaintext.= $_block ^ $_key; $_plaintext.= $_block ^ $_key;
@ -2897,7 +2901,7 @@ abstract class SymmetricKey
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$this->decryptIV = $_xor; $this->decryptIV = $_xor;
if ($_start = $_ciphertext_len % '.$block_size.') { if ($_start = $_ciphertext_len % ' . $block_size . ') {
$_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"]; $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
} }
} }
@ -2921,7 +2925,7 @@ abstract class SymmetricKey
$_i = 0; $_i = 0;
if ($_pos) { if ($_pos) {
$_orig_pos = $_pos; $_orig_pos = $_pos;
$_max = '.$block_size.' - $_pos; $_max = ' . $block_size . ' - $_pos;
if ($_len >= $_max) { if ($_len >= $_max) {
$_i = $_max; $_i = $_max;
$_len-= $_max; $_len-= $_max;
@ -2934,17 +2938,17 @@ abstract class SymmetricKey
$_ciphertext = substr($_iv, $_orig_pos) ^ $_text; $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
$_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i); $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
} }
while ($_len >= '.$block_size.') { while ($_len >= ' . $block_size . ') {
$in = $_iv; $in = $_iv;
'.$encrypt_block.'; ' . $encrypt_block . ';
$_iv = $in ^ substr($_text, $_i, '.$block_size.'); $_iv = $in ^ substr($_text, $_i, ' . $block_size . ');
$_ciphertext.= $_iv; $_ciphertext.= $_iv;
$_len-= '.$block_size.'; $_len-= ' . $block_size . ';
$_i+= '.$block_size.'; $_i+= ' . $block_size . ';
} }
if ($_len) { if ($_len) {
$in = $_iv; $in = $_iv;
'.$encrypt_block.' ' . $encrypt_block . '
$_iv = $in; $_iv = $in;
$_block = $_iv ^ substr($_text, $_i); $_block = $_iv ^ substr($_text, $_i);
$_iv = substr_replace($_iv, $_block, 0, $_len); $_iv = substr_replace($_iv, $_block, 0, $_len);
@ -2969,7 +2973,7 @@ abstract class SymmetricKey
$_i = 0; $_i = 0;
if ($_pos) { if ($_pos) {
$_orig_pos = $_pos; $_orig_pos = $_pos;
$_max = '.$block_size.' - $_pos; $_max = ' . $block_size . ' - $_pos;
if ($_len >= $_max) { if ($_len >= $_max) {
$_i = $_max; $_i = $_max;
$_len-= $_max; $_len-= $_max;
@ -2982,19 +2986,19 @@ abstract class SymmetricKey
$_plaintext = substr($_iv, $_orig_pos) ^ $_text; $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
$_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i); $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
} }
while ($_len >= '.$block_size.') { while ($_len >= ' . $block_size . ') {
$in = $_iv; $in = $_iv;
'.$encrypt_block.' ' . $encrypt_block . '
$_iv = $in; $_iv = $in;
$cb = substr($_text, $_i, '.$block_size.'); $cb = substr($_text, $_i, ' . $block_size . ');
$_plaintext.= $_iv ^ $cb; $_plaintext.= $_iv ^ $cb;
$_iv = $cb; $_iv = $cb;
$_len-= '.$block_size.'; $_len-= ' . $block_size . ';
$_i+= '.$block_size.'; $_i+= ' . $block_size . ';
} }
if ($_len) { if ($_len) {
$in = $_iv; $in = $_iv;
'.$encrypt_block.' ' . $encrypt_block . '
$_iv = $in; $_iv = $in;
$_plaintext.= $_iv ^ substr($_text, $_i); $_plaintext.= $_iv ^ substr($_text, $_i);
$_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len); $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
@ -3012,16 +3016,16 @@ abstract class SymmetricKey
for ($_i = 0; $_i < $_len; ++$_i) { for ($_i = 0; $_i < $_len; ++$_i) {
$in = $_iv; $in = $_iv;
'.$encrypt_block.' ' . $encrypt_block . '
$_ciphertext .= ($_c = $_text[$_i] ^ $in); $_ciphertext .= ($_c = $_text[$_i] ^ $in);
$_iv = substr($_iv, 1) . $_c; $_iv = substr($_iv, 1) . $_c;
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
if ($_len >= '.$block_size.') { if ($_len >= ' . $block_size . ') {
$this->encryptIV = substr($_ciphertext, -'.$block_size.'); $this->encryptIV = substr($_ciphertext, -' . $block_size . ');
} else { } else {
$this->encryptIV = substr($this->encryptIV, $_len - '.$block_size.') . substr($_ciphertext, -$_len); $this->encryptIV = substr($this->encryptIV, $_len - ' . $block_size . ') . substr($_ciphertext, -$_len);
} }
} }
@ -3034,16 +3038,16 @@ abstract class SymmetricKey
for ($_i = 0; $_i < $_len; ++$_i) { for ($_i = 0; $_i < $_len; ++$_i) {
$in = $_iv; $in = $_iv;
'.$encrypt_block.' ' . $encrypt_block . '
$_plaintext .= $_text[$_i] ^ $in; $_plaintext .= $_text[$_i] ^ $in;
$_iv = substr($_iv, 1) . $_text[$_i]; $_iv = substr($_iv, 1) . $_text[$_i];
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
if ($_len >= '.$block_size.') { if ($_len >= ' . $block_size . ') {
$this->decryptIV = substr($_text, -'.$block_size.'); $this->decryptIV = substr($_text, -' . $block_size . ');
} else { } else {
$this->decryptIV = substr($this->decryptIV, $_len - '.$block_size.') . substr($_text, -$_len); $this->decryptIV = substr($this->decryptIV, $_len - ' . $block_size . ') . substr($_text, -$_len);
} }
} }
@ -3058,7 +3062,7 @@ abstract class SymmetricKey
for ($_i = 0; $_i < $_len; ++$_i) { for ($_i = 0; $_i < $_len; ++$_i) {
$in = $_iv; $in = $_iv;
'.$encrypt_block.' ' . $encrypt_block . '
$_ciphertext.= $_text[$_i] ^ $in; $_ciphertext.= $_text[$_i] ^ $in;
$_iv = substr($_iv, 1) . $in[0]; $_iv = substr($_iv, 1) . $in[0];
} }
@ -3076,7 +3080,7 @@ abstract class SymmetricKey
for ($_i = 0; $_i < $_len; ++$_i) { for ($_i = 0; $_i < $_len; ++$_i) {
$in = $_iv; $in = $_iv;
'.$encrypt_block.' ' . $encrypt_block . '
$_plaintext.= $_text[$_i] ^ $in; $_plaintext.= $_text[$_i] ^ $in;
$_iv = substr($_iv, 1) . $in[0]; $_iv = substr($_iv, 1) . $in[0];
} }
@ -3096,29 +3100,29 @@ abstract class SymmetricKey
$_buffer = &$this->enbuffer; $_buffer = &$this->enbuffer;
if (strlen($_buffer["xor"])) { if (strlen($_buffer["xor"])) {
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
$_block = substr($_text, $_i, '.$block_size.'); $_block = substr($_text, $_i, ' . $block_size . ');
if (strlen($_block) > strlen($_buffer["xor"])) { if (strlen($_block) > strlen($_buffer["xor"])) {
$in = $_xor; $in = $_xor;
'.$encrypt_block.' ' . $encrypt_block . '
$_xor = $in; $_xor = $in;
$_buffer["xor"].= $_xor; $_buffer["xor"].= $_xor;
} }
$_key = \phpseclib3\Common\Functions\Strings::shift($_buffer["xor"], '.$block_size.'); $_key = \phpseclib3\Common\Functions\Strings::shift($_buffer["xor"], ' . $block_size . ');
$_ciphertext.= $_block ^ $_key; $_ciphertext.= $_block ^ $_key;
} }
} else { } else {
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
$in = $_xor; $in = $_xor;
'.$encrypt_block.' ' . $encrypt_block . '
$_xor = $in; $_xor = $in;
$_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor; $_ciphertext.= substr($_text, $_i, ' . $block_size . ') ^ $_xor;
} }
$_key = $_xor; $_key = $_xor;
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$this->encryptIV = $_xor; $this->encryptIV = $_xor;
if ($_start = $_plaintext_len % '.$block_size.') { if ($_start = $_plaintext_len % ' . $block_size . ') {
$_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"]; $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
} }
} }
@ -3132,29 +3136,29 @@ abstract class SymmetricKey
$_buffer = &$this->debuffer; $_buffer = &$this->debuffer;
if (strlen($_buffer["xor"])) { if (strlen($_buffer["xor"])) {
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
$_block = substr($_text, $_i, '.$block_size.'); $_block = substr($_text, $_i, ' . $block_size . ');
if (strlen($_block) > strlen($_buffer["xor"])) { if (strlen($_block) > strlen($_buffer["xor"])) {
$in = $_xor; $in = $_xor;
'.$encrypt_block.' ' . $encrypt_block . '
$_xor = $in; $_xor = $in;
$_buffer["xor"].= $_xor; $_buffer["xor"].= $_xor;
} }
$_key = \phpseclib3\Common\Functions\Strings::shift($_buffer["xor"], '.$block_size.'); $_key = \phpseclib3\Common\Functions\Strings::shift($_buffer["xor"], ' . $block_size . ');
$_plaintext.= $_block ^ $_key; $_plaintext.= $_block ^ $_key;
} }
} else { } else {
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
$in = $_xor; $in = $_xor;
'.$encrypt_block.' ' . $encrypt_block . '
$_xor = $in; $_xor = $in;
$_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor; $_plaintext.= substr($_text, $_i, ' . $block_size . ') ^ $_xor;
} }
$_key = $_xor; $_key = $_xor;
} }
if ($this->continuousBuffer) { if ($this->continuousBuffer) {
$this->decryptIV = $_xor; $this->decryptIV = $_xor;
if ($_start = $_ciphertext_len % '.$block_size.') { if ($_start = $_ciphertext_len % ' . $block_size . ') {
$_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"]; $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
} }
} }
@ -3164,12 +3168,12 @@ abstract class SymmetricKey
case self::MODE_STREAM: case self::MODE_STREAM:
$encrypt = $init_encrypt . ' $encrypt = $init_encrypt . '
$_ciphertext = ""; $_ciphertext = "";
'.$encrypt_block.' ' . $encrypt_block . '
return $_ciphertext; return $_ciphertext;
'; ';
$decrypt = $init_decrypt . ' $decrypt = $init_decrypt . '
$_plaintext = ""; $_plaintext = "";
'.$decrypt_block.' ' . $decrypt_block . '
return $_plaintext; return $_plaintext;
'; ';
break; break;
@ -3181,9 +3185,9 @@ abstract class SymmetricKey
$in = $this->encryptIV; $in = $this->encryptIV;
for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_plaintext_len; $_i+= ' . $block_size . ') {
$in = substr($_text, $_i, '.$block_size.') ^ $in; $in = substr($_text, $_i, ' . $block_size . ') ^ $in;
'.$encrypt_block.' ' . $encrypt_block . '
$_ciphertext.= $in; $_ciphertext.= $in;
} }
@ -3196,14 +3200,14 @@ abstract class SymmetricKey
$decrypt = $init_decrypt . ' $decrypt = $init_decrypt . '
$_plaintext = ""; $_plaintext = "";
$_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0)); $_text = str_pad($_text, strlen($_text) + (' . $block_size . ' - strlen($_text) % ' . $block_size . ') % ' . $block_size . ', chr(0));
$_ciphertext_len = strlen($_text); $_ciphertext_len = strlen($_text);
$_iv = $this->decryptIV; $_iv = $this->decryptIV;
for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { for ($_i = 0; $_i < $_ciphertext_len; $_i+= ' . $block_size . ') {
$in = $_block = substr($_text, $_i, '.$block_size.'); $in = $_block = substr($_text, $_i, ' . $block_size . ');
'.$decrypt_block.' ' . $decrypt_block . '
$_plaintext.= $in ^ $_iv; $_plaintext.= $in ^ $_iv;
$_iv = $_block; $_iv = $_block;
} }
@ -3381,7 +3385,7 @@ abstract class SymmetricKey
$s = $this->poly1305Key; // strlen($this->poly1305Key) == 32 $s = $this->poly1305Key; // strlen($this->poly1305Key) == 32
$r = Strings::shift($s, 16); $r = Strings::shift($s, 16);
$r = strrev($r); $r = strrev($r);
$r&= "\x0f\xff\xff\xfc\x0f\xff\xff\xfc\x0f\xff\xff\xfc\x0f\xff\xff\xff"; $r &= "\x0f\xff\xff\xfc\x0f\xff\xff\xfc\x0f\xff\xff\xfc\x0f\xff\xff\xff";
$s = strrev($s); $s = strrev($s);
$r = self::$poly1305Field->newInteger(new BigInteger($r, 256)); $r = self::$poly1305Field->newInteger(new BigInteger($r, 256));

View File

@ -1248,7 +1248,7 @@ class DES extends BlockCipher
self::ENCRYPT => [], self::ENCRYPT => [],
self::DECRYPT => array_fill(0, 32, 0) self::DECRYPT => array_fill(0, 32, 0)
]; ];
for ($i = 0, $ki = 31; $i < 16; ++$i, $ki-= 2) { for ($i = 0, $ki = 31; $i < 16; ++$i, $ki -= 2) {
$c <<= $shifts[$i]; $c <<= $shifts[$i];
$c = ($c | ($c >> 28)) & 0x0FFFFFFF; $c = ($c | ($c >> 28)) & 0x0FFFFFFF;
$d <<= $shifts[$i]; $d <<= $shifts[$i];
@ -1367,7 +1367,7 @@ class DES extends BlockCipher
// start of "the Feistel (F) function" - see the following URL: // start of "the Feistel (F) function" - see the following URL:
// http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png
// Merge key schedule. // Merge key schedule.
$crypt_block[$c].= ' $crypt_block[$c] .= '
$b1 = ((' . $r . ' >> 3) & 0x1FFFFFFF) ^ (' . $r . ' << 29) ^ ' . $k[$c][++$ki] . '; $b1 = ((' . $r . ' >> 3) & 0x1FFFFFFF) ^ (' . $r . ' << 29) ^ ' . $k[$c][++$ki] . ';
$b2 = ((' . $r . ' >> 31) & 0x00000001) ^ (' . $r . ' << 1) ^ ' . $k[$c][++$ki] . ';' . $b2 = ((' . $r . ' >> 31) & 0x00000001) ^ (' . $r . ' << 1) ^ ' . $k[$c][++$ki] . ';' .
/* S-box indexing. */ /* S-box indexing. */
@ -1385,7 +1385,7 @@ class DES extends BlockCipher
} }
// Perform the inverse IP permutation. // Perform the inverse IP permutation.
$crypt_block[$c].= '$in = $crypt_block[$c] .= '$in =
($shuffleinvip[($l >> 24) & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | ($shuffleinvip[($l >> 24) & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") |
($shuffleinvip[($r >> 24) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | ($shuffleinvip[($r >> 24) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") |
($shuffleinvip[($l >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | ($shuffleinvip[($l >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") |

View File

@ -82,7 +82,7 @@ abstract class DH extends AsymmetricKey
*/ */
public static function createParameters(...$args) public static function createParameters(...$args)
{ {
$params = new Parameters; $params = new Parameters();
if (count($args) == 2 && $args[0] instanceof BigInteger && $args[1] instanceof BigInteger) { if (count($args) == 2 && $args[0] instanceof BigInteger && $args[1] instanceof BigInteger) {
//if (!$args[0]->isPrime()) { //if (!$args[0]->isPrime()) {
// throw new \InvalidArgumentException('The first parameter should be a prime number'); // throw new \InvalidArgumentException('The first parameter should be a prime number');
@ -252,7 +252,7 @@ abstract class DH extends AsymmetricKey
$max = $params->prime->subtract($one); $max = $params->prime->subtract($one);
} }
$key = new PrivateKey; $key = new PrivateKey();
$key->prime = $params->prime; $key->prime = $params->prime;
$key->base = $params->base; $key->base = $params->base;
$key->privateKey = BigInteger::randomRange($one, $max); $key->privateKey = BigInteger::randomRange($one, $max);
@ -324,7 +324,8 @@ abstract class DH extends AsymmetricKey
{ {
try { try {
return EC::load($key, $password); return EC::load($key, $password);
} catch (NoKeyLoadedException $e) {} } catch (NoKeyLoadedException $e) {
}
return parent::load($key, $password); return parent::load($key, $password);
} }
@ -339,11 +340,11 @@ abstract class DH extends AsymmetricKey
protected static function onLoad($components) protected static function onLoad($components)
{ {
if (!isset($components['privateKey']) && !isset($components['publicKey'])) { if (!isset($components['privateKey']) && !isset($components['publicKey'])) {
$new = new Parameters; $new = new Parameters();
} else { } else {
$new = isset($components['privateKey']) ? $new = isset($components['privateKey']) ?
new PrivateKey : new PrivateKey() :
new PublicKey; new PublicKey();
} }
$new->prime = $components['prime']; $new->prime = $components['prime'];

View File

@ -169,7 +169,7 @@ abstract class DSA extends AsymmetricKey
$h = $h->add(self::$one); $h = $h->add(self::$one);
} }
$dsa = new Parameters; $dsa = new Parameters();
$dsa->p = $p; $dsa->p = $p;
$dsa->q = $q; $dsa->q = $q;
$dsa->g = $g; $dsa->g = $g;
@ -199,15 +199,15 @@ abstract class DSA extends AsymmetricKey
if (count($args) == 2 && is_int($args[0]) && is_int($args[1])) { if (count($args) == 2 && is_int($args[0]) && is_int($args[1])) {
$params = self::createParameters($args[0], $args[1]); $params = self::createParameters($args[0], $args[1]);
} else if (count($args) == 1 && $args[0] instanceof Parameters) { } elseif (count($args) == 1 && $args[0] instanceof Parameters) {
$params = $args[0]; $params = $args[0];
} else if (!count($args)) { } elseif (!count($args)) {
$params = self::createParameters(); $params = self::createParameters();
} else { } else {
throw new InsufficientSetupException('Valid parameters are either two integers (L and N), a single DSA object or no parameters at all.'); throw new InsufficientSetupException('Valid parameters are either two integers (L and N), a single DSA object or no parameters at all.');
} }
$private = new PrivateKey; $private = new PrivateKey();
$private->p = $params->p; $private->p = $params->p;
$private->q = $params->q; $private->q = $params->q;
$private->g = $params->g; $private->g = $params->g;
@ -237,12 +237,12 @@ abstract class DSA extends AsymmetricKey
} }
if (!isset($components['x']) && !isset($components['y'])) { if (!isset($components['x']) && !isset($components['y'])) {
$new = new Parameters; $new = new Parameters();
} else if (isset($components['x'])) { } elseif (isset($components['x'])) {
$new = new PrivateKey; $new = new PrivateKey();
$new->x = $components['x']; $new->x = $components['x'];
} else { } else {
$new = new PublicKey; $new = new PublicKey();
} }
$new->p = $components['p']; $new->p = $components['p'];

View File

@ -70,7 +70,9 @@ abstract class SSH2
if ($r->getLength() > 160 || $s->getLength() > 160) { if ($r->getLength() > 160 || $s->getLength() > 160) {
return false; return false;
} }
return Strings::packSSH2('ss', 'ssh-dss', return Strings::packSSH2(
'ss',
'ssh-dss',
str_pad($r->toBytes(), 20, "\0", STR_PAD_LEFT) . str_pad($r->toBytes(), 20, "\0", STR_PAD_LEFT) .
str_pad($s->toBytes(), 20, "\0", STR_PAD_LEFT) str_pad($s->toBytes(), 20, "\0", STR_PAD_LEFT)
); );

View File

@ -158,7 +158,7 @@ abstract class EC extends AsymmetricKey
return $privatekey; return $privatekey;
} }
$privatekey = new PrivateKey; $privatekey = new PrivateKey();
$curveName = $curve; $curveName = $curve;
if (preg_match('#(?:^curve|^ed)\d+$#', $curveName)) { if (preg_match('#(?:^curve|^ed)\d+$#', $curveName)) {
@ -217,14 +217,14 @@ abstract class EC extends AsymmetricKey
} }
if (!isset($components['dA']) && !isset($components['QA'])) { if (!isset($components['dA']) && !isset($components['QA'])) {
$new = new Parameters; $new = new Parameters();
$new->curve = $components['curve']; $new->curve = $components['curve'];
return $new; return $new;
} }
$new = isset($components['dA']) ? $new = isset($components['dA']) ?
new PrivateKey : new PrivateKey() :
new PublicKey; new PublicKey();
$new->curve = $components['curve']; $new->curve = $components['curve'];
$new->QA = $components['QA']; $new->QA = $components['QA'];

View File

@ -139,7 +139,7 @@ class KoblitzPrime extends Prime
]; ];
if (isset($p['naf'])) { if (isset($p['naf'])) {
$beta['naf'] = array_map(function($p) { $beta['naf'] = array_map(function ($p) {
return [ return [
$p[0]->multiply($this->beta), $p[0]->multiply($this->beta),
$p[1], $p[1],
@ -202,7 +202,8 @@ class KoblitzPrime extends Prime
$f = $e->multiply($e); $f = $e->multiply($e);
$x3 = $f->subtract($this->two->multiply($d)); $x3 = $f->subtract($this->two->multiply($d));
$y3 = $e->multiply($d->subtract($x3))->subtract( $y3 = $e->multiply($d->subtract($x3))->subtract(
$this->eight->multiply($c)); $this->eight->multiply($c)
);
$z3 = $this->two->multiply($y1)->multiply($z1); $z3 = $this->two->multiply($y1)->multiply($z1);
return [$x3, $y3, $z3]; return [$x3, $y3, $z3];
} }

View File

@ -207,8 +207,10 @@ class Prime extends Base
$v = $u1->multiply($h2); $v = $u1->multiply($h2);
$x3 = $r->multiply($r)->subtract($h3)->subtract($v->multiply($this->two)); $x3 = $r->multiply($r)->subtract($h3)->subtract($v->multiply($this->two));
$y3 = $r->multiply( $y3 = $r->multiply(
$v->subtract($x3))->subtract( $v->subtract($x3)
$s1->multiply($h3)); )->subtract(
$s1->multiply($h3)
);
return [$x3, $y3, $h]; return [$x3, $y3, $h];
} }
@ -242,8 +244,10 @@ class Prime extends Base
$v = $u1->multiply($h2); $v = $u1->multiply($h2);
$x3 = $r->multiply($r)->subtract($h3)->subtract($v->multiply($this->two)); $x3 = $r->multiply($r)->subtract($h3)->subtract($v->multiply($this->two));
$y3 = $r->multiply( $y3 = $r->multiply(
$v->subtract($x3))->subtract( $v->subtract($x3)
$s1->multiply($h3)); )->subtract(
$s1->multiply($h3)
);
$z3 = $h->multiply($z1); $z3 = $h->multiply($z1);
return [$x3, $y3, $z3]; return [$x3, $y3, $z3];
} }
@ -279,8 +283,10 @@ class Prime extends Base
$v = $u1->multiply($h2); $v = $u1->multiply($h2);
$x3 = $r->multiply($r)->subtract($h3)->subtract($v->multiply($this->two)); $x3 = $r->multiply($r)->subtract($h3)->subtract($v->multiply($this->two));
$y3 = $r->multiply( $y3 = $r->multiply(
$v->subtract($x3))->subtract( $v->subtract($x3)
$s1->multiply($h3)); )->subtract(
$s1->multiply($h3)
);
$z3 = $h->multiply($z1)->multiply($z2); $z3 = $h->multiply($z1)->multiply($z2);
return [$x3, $y3, $z3]; return [$x3, $y3, $z3];
} }
@ -370,7 +376,8 @@ class Prime extends Base
$m = $m1->add($m2); $m = $m1->add($m2);
$x1 = $m->multiply($m)->subtract($this->two->multiply($s)); $x1 = $m->multiply($m)->subtract($this->two->multiply($s));
$y1 = $m->multiply($s->subtract($x1))->subtract( $y1 = $m->multiply($s->subtract($x1))->subtract(
$this->eight->multiply($y2->multiply($y2))); $this->eight->multiply($y2->multiply($y2))
);
$z1 = $this->two->multiply($y)->multiply($z); $z1 = $this->two->multiply($y)->multiply($z);
return [$x1, $y1, $z1]; return [$x1, $y1, $z1];
} }
@ -390,7 +397,8 @@ class Prime extends Base
$m = $m1->add($this->a); $m = $m1->add($this->a);
$x1 = $m->multiply($m)->subtract($this->two->multiply($s)); $x1 = $m->multiply($m)->subtract($this->two->multiply($s));
$y1 = $m->multiply($s->subtract($x1))->subtract( $y1 = $m->multiply($s->subtract($x1))->subtract(
$this->eight->multiply($y2->multiply($y2))); $this->eight->multiply($y2->multiply($y2))
);
$z1 = $this->two->multiply($y); $z1 = $this->two->multiply($y);
return [$x1, $y1, $z1]; return [$x1, $y1, $z1];
} }
@ -439,8 +447,12 @@ class Prime extends Base
$x = new BigInteger($m, 256); $x = new BigInteger($m, 256);
$xp = $this->convertInteger($x); $xp = $this->convertInteger($x);
switch ($y) { switch ($y) {
case 2: $ypn = false; break; case 2:
case 3: $ypn = true; break; $ypn = false;
break;
case 3:
$ypn = true;
break;
default: default:
throw new \RuntimeException('Coordinate not in recognized format'); throw new \RuntimeException('Coordinate not in recognized format');
} }
@ -529,7 +541,7 @@ class Prime extends Base
// comb all window NAFs // comb all window NAFs
$max = 0; $max = 0;
for ($i = $length - 1; $i >= 1; $i-= 2) { for ($i = $length - 1; $i >= 1; $i -= 2) {
$a = $i - 1; $a = $i - 1;
$b = $i; $b = $i;
if ($wndWidth[$a] != 1 || $wndWidth[$b] != 1) { if ($wndWidth[$a] != 1 || $wndWidth[$b] != 1) {
@ -687,12 +699,12 @@ class Prime extends Base
while ($k1->compare(new BigInteger(-$d1)) > 0 || $k2->compare(new BigInteger(-$d2)) > 0) { while ($k1->compare(new BigInteger(-$d1)) > 0 || $k2->compare(new BigInteger(-$d2)) > 0) {
// first phase // first phase
$m14 = $k1->testBit(0) + 2 * $k1->testBit(1); $m14 = $k1->testBit(0) + 2 * $k1->testBit(1);
$m14+= $d1; $m14 += $d1;
$m14&= 3; $m14 &= 3;
$m24 = $k2->testBit(0) + 2 * $k2->testBit(1); $m24 = $k2->testBit(0) + 2 * $k2->testBit(1);
$m24+= $d2; $m24 += $d2;
$m24&= 3; $m24 &= 3;
if ($m14 == 3) { if ($m14 == 3) {
$m14 = -1; $m14 = -1;
@ -704,8 +716,8 @@ class Prime extends Base
$u1 = 0; $u1 = 0;
if ($m14 & 1) { // if $m14 is odd if ($m14 & 1) { // if $m14 is odd
$m8 = $k1->testBit(0) + 2 * $k1->testBit(1) + 4 * $k1->testBit(2); $m8 = $k1->testBit(0) + 2 * $k1->testBit(1) + 4 * $k1->testBit(2);
$m8+= $d1; $m8 += $d1;
$m8&= 7; $m8 &= 7;
$u1 = ($m8 == 3 || $m8 == 5) && $m24 == 2 ? -$m14 : $m14; $u1 = ($m8 == 3 || $m8 == 5) && $m24 == 2 ? -$m14 : $m14;
} }
$jsf[0][] = $u1; $jsf[0][] = $u1;
@ -713,8 +725,8 @@ class Prime extends Base
$u2 = 0; $u2 = 0;
if ($m24 & 1) { // if $m24 is odd if ($m24 & 1) { // if $m24 is odd
$m8 = $k2->testBit(0) + 2 * $k2->testBit(1) + 4 * $k2->testBit(2); $m8 = $k2->testBit(0) + 2 * $k2->testBit(1) + 4 * $k2->testBit(2);
$m8+= $d2; $m8 += $d2;
$m8&= 7; $m8 &= 7;
$u2 = ($m8 == 3 || $m8 == 5) && $m14 == 2 ? -$m24 : $m24; $u2 = ($m8 == 3 || $m8 == 5) && $m14 == 2 ? -$m24 : $m24;
} }
$jsf[1][] = $u2; $jsf[1][] = $u2;

View File

@ -53,9 +53,9 @@ class Curve25519 extends Montgomery
//return [$this->factory->newInteger(new BigInteger($r, 256))]; //return [$this->factory->newInteger(new BigInteger($r, 256))];
$d = $d->toBytes(); $d = $d->toBytes();
$d&= "\xF8" . str_repeat("\xFF", 30) . "\x7F"; $d &= "\xF8" . str_repeat("\xFF", 30) . "\x7F";
$d = strrev($d); $d = strrev($d);
$d|= "\x40"; $d |= "\x40";
$d = new BigInteger($d, -256); $d = new BigInteger($d, -256);
return parent::multiplyPoint($p, $d); return parent::multiplyPoint($p, $d);

View File

@ -25,13 +25,17 @@ class Curve448 extends Montgomery
// 2^448 - 2^224 - 1 // 2^448 - 2^224 - 1
$this->setModulo(new BigInteger( $this->setModulo(new BigInteger(
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE' . 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE' .
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 16)); 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
16
));
$this->a24 = $this->factory->newInteger(new BigInteger('39081')); $this->a24 = $this->factory->newInteger(new BigInteger('39081'));
$this->p = [$this->factory->newInteger(new BigInteger(5))]; $this->p = [$this->factory->newInteger(new BigInteger(5))];
// 2^446 - 0x8335dc163bb124b65129c96fde933d8d723a70aadc873d6d54a7bb0d // 2^446 - 0x8335dc163bb124b65129c96fde933d8d723a70aadc873d6d54a7bb0d
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' . '3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' .
'7CCA23E9C44EDB49AED63690216CC2728DC58F552378C292AB5844F3', 16)); '7CCA23E9C44EDB49AED63690216CC2728DC58F552378C292AB5844F3',
16
));
/* /*
$this->setCoefficients( $this->setCoefficients(
@ -62,7 +66,7 @@ class Curve448 extends Montgomery
$d = $d->toBytes(); $d = $d->toBytes();
$d[0] = $d[0] & "\xFC"; $d[0] = $d[0] & "\xFC";
$d = strrev($d); $d = strrev($d);
$d|= "\x80"; $d |= "\x80";
$d = new BigInteger($d, 256); $d = new BigInteger($d, 256);
return parent::multiplyPoint($p, $d); return parent::multiplyPoint($p, $d);

View File

@ -29,7 +29,9 @@ class Ed448 extends TwistedEdwards
// 2^448 - 2^224 - 1 // 2^448 - 2^224 - 1
$this->setModulo(new BigInteger( $this->setModulo(new BigInteger(
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE' . 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE' .
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 16)); 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
16
));
$this->setCoefficients( $this->setCoefficients(
new BigInteger(1), new BigInteger(1),
// -39081 // -39081
@ -44,7 +46,9 @@ class Ed448 extends TwistedEdwards
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' . '3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' .
'7CCA23E9C44EDB49AED63690216CC2728DC58F552378C292AB5844F3', 16)); '7CCA23E9C44EDB49AED63690216CC2728DC58F552378C292AB5844F3',
16
));
} }
/** /**

View File

@ -24,25 +24,37 @@ class brainpoolP384r1 extends Prime
{ {
$this->setModulo(new BigInteger( $this->setModulo(new BigInteger(
'8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A7' . '8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A7' .
'1874700133107EC53', 16)); '1874700133107EC53',
16
));
$this->setCoefficients( $this->setCoefficients(
new BigInteger( new BigInteger(
'7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503' . '7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503' .
'AD4EB04A8C7DD22CE2826', 16), 'AD4EB04A8C7DD22CE2826',
16
),
new BigInteger( new BigInteger(
'4A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DB' . '4A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DB' .
'C9943AB78696FA504C11', 16) 'C9943AB78696FA504C11',
16
)
); );
$this->setBasePoint( $this->setBasePoint(
new BigInteger( new BigInteger(
'1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D' . '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D' .
'646AAEF87B2E247D4AF1E', 16), '646AAEF87B2E247D4AF1E',
16
),
new BigInteger( new BigInteger(
'8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E464621779' . '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E464621779' .
'1811142820341263C5315', 16) '1811142820341263C5315',
16
)
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC31' . '8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC31' .
'03B883202E9046565', 16)); '03B883202E9046565',
16
));
} }
} }

View File

@ -24,25 +24,37 @@ class brainpoolP384t1 extends Prime
{ {
$this->setModulo(new BigInteger( $this->setModulo(new BigInteger(
'8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A7' . '8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A7' .
'1874700133107EC53', 16)); '1874700133107EC53',
16
));
$this->setCoefficients( $this->setCoefficients(
new BigInteger( new BigInteger(
'8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901' . '8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901' .
'D1A71874700133107EC50', 16), // eg. -3 'D1A71874700133107EC50',
16
), // eg. -3
new BigInteger( new BigInteger(
'7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B8' . '7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B8' .
'8805CED70355A33B471EE', 16) '8805CED70355A33B471EE',
16
)
); );
$this->setBasePoint( $this->setBasePoint(
new BigInteger( new BigInteger(
'18DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946' . '18DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946' .
'A5F54D8D0AA2F418808CC', 16), 'A5F54D8D0AA2F418808CC',
16
),
new BigInteger( new BigInteger(
'25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC' . '25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC' .
'2B2912675BF5B9E582928', 16) '2B2912675BF5B9E582928',
16
)
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC31' . '8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC31' .
'03B883202E9046565', 16)); '03B883202E9046565',
16
));
} }
} }

View File

@ -24,25 +24,37 @@ class brainpoolP512r1 extends Prime
{ {
$this->setModulo(new BigInteger( $this->setModulo(new BigInteger(
'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC' . 'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC' .
'66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3', 16)); '66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3',
16
));
$this->setCoefficients( $this->setCoefficients(
new BigInteger( new BigInteger(
'7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA82' . '7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA82' .
'53AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA', 16), '53AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA',
16
),
new BigInteger( new BigInteger(
'3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C' . '3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C' .
'1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723', 16) '1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723',
16
)
); );
$this->setBasePoint( $this->setBasePoint(
new BigInteger( new BigInteger(
'81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D' . '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D' .
'0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822', 16), '0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',
16
),
new BigInteger( new BigInteger(
'7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5' . '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5' .
'F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892', 16) 'F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892',
16
)
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA' . 'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA' .
'92619418661197FAC10471DB1D381085DDADDB58796829CA90069', 16)); '92619418661197FAC10471DB1D381085DDADDB58796829CA90069',
16
));
} }
} }

View File

@ -24,25 +24,37 @@ class brainpoolP512t1 extends Prime
{ {
$this->setModulo(new BigInteger( $this->setModulo(new BigInteger(
'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC' . 'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC' .
'66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3', 16)); '66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3',
16
));
$this->setCoefficients( $this->setCoefficients(
new BigInteger( new BigInteger(
'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC' . 'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC' .
'66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F0', 16), // eg. -3 '66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F0',
16
), // eg. -3
new BigInteger( new BigInteger(
'7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA23049' . '7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA23049' .
'76540F6450085F2DAE145C22553B465763689180EA2571867423E', 16) '76540F6450085F2DAE145C22553B465763689180EA2571867423E',
16
)
); );
$this->setBasePoint( $this->setBasePoint(
new BigInteger( new BigInteger(
'640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CD' . '640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CD' .
'B3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA', 16), 'B3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA',
16
),
new BigInteger( new BigInteger(
'5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEE' . '5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEE' .
'F216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332', 16) 'F216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332',
16
)
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA' . 'AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA' .
'92619418661197FAC10471DB1D381085DDADDB58796829CA90069', 16)); '92619418661197FAC10471DB1D381085DDADDB58796829CA90069',
16
));
} }
} }

View File

@ -33,7 +33,8 @@ class sect409k1 extends Binary
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F' . '7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F' .
'83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF', 16 '83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF',
16
)); ));
} }
} }

View File

@ -33,7 +33,8 @@ class sect409r1 extends Binary
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'010000000000000000000000000000000000000000000000000001E2' . '010000000000000000000000000000000000000000000000000001E2' .
'AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173', 16 'AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173',
16
)); ));
} }
} }

View File

@ -37,7 +37,8 @@ class sect571k1 extends Binary
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'020000000000000000000000000000000000000000000000000000000000000000000000' . '020000000000000000000000000000000000000000000000000000000000000000000000' .
'131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001', 16 '131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001',
16
)); ));
} }
} }

View File

@ -37,7 +37,8 @@ class sect571r1 extends Binary
); );
$this->setOrder(new BigInteger( $this->setOrder(new BigInteger(
'03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' . '03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' .
'E661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47', 16 'E661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47',
16
)); ));
} }
} }

View File

@ -97,8 +97,8 @@ trait Common
'sect163k1' => '1.3.132.0.1', 'sect163k1' => '1.3.132.0.1',
'sect163r2' => '1.3.132.0.15', 'sect163r2' => '1.3.132.0.15',
'secp224r1' => '1.3.132.0.33', 'secp224r1' => '1.3.132.0.33',
'sect233k1'=> '1.3.132.0.26', 'sect233k1' => '1.3.132.0.26',
'sect233r1'=> '1.3.132.0.27', 'sect233r1' => '1.3.132.0.27',
'secp256r1' => '1.2.840.10045.3.1.7', // aka prime256v1 'secp256r1' => '1.2.840.10045.3.1.7', // aka prime256v1
'sect283k1' => '1.3.132.0.16', 'sect283k1' => '1.3.132.0.16',
'sect283r1' => '1.3.132.0.17', 'sect283r1' => '1.3.132.0.17',

View File

@ -56,10 +56,10 @@ abstract class MontgomeryPrivate
{ {
switch (strlen($key)) { switch (strlen($key)) {
case 32: case 32:
$curve = new Curve25519; $curve = new Curve25519();
break; break;
case 56: case 56:
$curve = new Curve448; $curve = new Curve448();
break; break;
default: default:
throw new \LengthException('The only supported lengths are 32 and 56'); throw new \LengthException('The only supported lengths are 32 and 56');

View File

@ -48,10 +48,10 @@ abstract class MontgomeryPublic
{ {
switch (strlen($key)) { switch (strlen($key)) {
case 32: case 32:
$curve = new Curve25519; $curve = new Curve25519();
break; break;
case 56: case 56:
$curve = new Curve448; $curve = new Curve448();
break; break;
default: default:
throw new \LengthException('The only supported lengths are 32 and 56'); throw new \LengthException('The only supported lengths are 32 and 56');

View File

@ -65,7 +65,7 @@ abstract class OpenSSH extends Progenitor
if ($type != $parsed['type']) { if ($type != $parsed['type']) {
throw new \RuntimeException("The public and private keys are not of the same type ($type vs $parsed[type])"); throw new \RuntimeException("The public and private keys are not of the same type ($type vs $parsed[type])");
} }
if ($type == 'ssh-ed25519' ) { if ($type == 'ssh-ed25519') {
list(, $key, $comment) = Strings::unpackSSH2('sss', $paddedKey); list(, $key, $comment) = Strings::unpackSSH2('sss', $paddedKey);
$key = libsodium::load($key); $key = libsodium::load($key);
$key['comment'] = $comment; $key['comment'] = $comment;
@ -117,7 +117,7 @@ abstract class OpenSSH extends Progenitor
$name = $reflect->getShortName(); $name = $reflect->getShortName();
$oid = self::$curveOIDs[$name]; $oid = self::$curveOIDs[$name];
$aliases = array_filter(self::$curveOIDs, function($v) use ($oid) { $aliases = array_filter(self::$curveOIDs, function ($v) use ($oid) {
return $v == $oid; return $v == $oid;
}); });
$aliases = array_keys($aliases); $aliases = array_keys($aliases);

View File

@ -113,7 +113,7 @@ abstract class PuTTY extends Progenitor
if (!$curve instanceof TwistedEdwardsCurve) { if (!$curve instanceof TwistedEdwardsCurve) {
$private = $privateKey->toBytes(); $private = $privateKey->toBytes();
if (!(strlen($privateKey->toBits()) & 7)) { if (!(strlen($privateKey->toBits()) & 7)) {
$private ="\0$private"; $private = "\0$private";
} }
} }

View File

@ -125,7 +125,7 @@ abstract class XML
$query = '/'; $query = '/';
$names = explode('/', $name); $names = explode('/', $name);
foreach ($names as $name) { foreach ($names as $name) {
$query.= "/*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='$name']"; $query .= "/*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='$name']";
} }
$result = $xpath->query($query); $result = $xpath->query($query);
if (!isset($error)) { if (!isset($error)) {
@ -435,7 +435,7 @@ abstract class XML
$temp = $result['specifiedCurve']; $temp = $result['specifiedCurve'];
switch ($temp['fieldID']['fieldType']) { switch ($temp['fieldID']['fieldType']) {
case 'prime-field': case 'prime-field':
$xml.= '<' . $pre . 'PrimeFieldParamsType>' . "\r\n" . $xml .= '<' . $pre . 'PrimeFieldParamsType>' . "\r\n" .
'<' . $pre . 'P>' . $temp['fieldID']['parameters'] . '</' . $pre . 'P>' . "\r\n" . '<' . $pre . 'P>' . $temp['fieldID']['parameters'] . '</' . $pre . 'P>' . "\r\n" .
'</' . $pre . 'PrimeFieldParamsType>' . "\r\n"; '</' . $pre . 'PrimeFieldParamsType>' . "\r\n";
$a = $curve->getA(); $a = $curve->getA();
@ -445,7 +445,7 @@ abstract class XML
default: default:
throw new UnsupportedCurveException('Field Type of ' . $temp['fieldID']['fieldType'] . ' is not supported'); throw new UnsupportedCurveException('Field Type of ' . $temp['fieldID']['fieldType'] . ' is not supported');
} }
$xml.= '</' . $pre . 'FieldParams>' . "\r\n" . $xml .= '</' . $pre . 'FieldParams>' . "\r\n" .
'<' . $pre . 'CurveParamsType>' . "\r\n" . '<' . $pre . 'CurveParamsType>' . "\r\n" .
'<' . $pre . 'A>' . $a . '</' . $pre . 'A>' . "\r\n" . '<' . $pre . 'A>' . $a . '</' . $pre . 'A>' . "\r\n" .
'<' . $pre . 'B>' . $b . '</' . $pre . 'B>' . "\r\n" . '<' . $pre . 'B>' . $b . '</' . $pre . 'B>' . "\r\n" .
@ -470,14 +470,14 @@ abstract class XML
$temp = $result['specifiedCurve']; $temp = $result['specifiedCurve'];
switch ($temp['fieldID']['fieldType']) { switch ($temp['fieldID']['fieldType']) {
case 'prime-field': case 'prime-field':
$xml.= '<' . $pre . 'Prime>' . "\r\n" . $xml .= '<' . $pre . 'Prime>' . "\r\n" .
'<' . $pre . 'P>' . Base64::encode($temp['fieldID']['parameters']->toBytes()) . '</' . $pre . 'P>' . "\r\n" . '<' . $pre . 'P>' . Base64::encode($temp['fieldID']['parameters']->toBytes()) . '</' . $pre . 'P>' . "\r\n" .
'</' . $pre . 'Prime>' . "\r\n" ; '</' . $pre . 'Prime>' . "\r\n" ;
break; break;
default: default:
throw new UnsupportedCurveException('Field Type of ' . $temp['fieldID']['fieldType'] . ' is not supported'); throw new UnsupportedCurveException('Field Type of ' . $temp['fieldID']['fieldType'] . ' is not supported');
} }
$xml.= '</' . $pre . 'FieldID>' . "\r\n" . $xml .= '</' . $pre . 'FieldID>' . "\r\n" .
'<' . $pre . 'Curve>' . "\r\n" . '<' . $pre . 'Curve>' . "\r\n" .
'<' . $pre . 'A>' . Base64::encode($temp['curve']['a']) . '</' . $pre . 'A>' . "\r\n" . '<' . $pre . 'A>' . Base64::encode($temp['curve']['a']) . '</' . $pre . 'A>' . "\r\n" .
'<' . $pre . 'B>' . Base64::encode($temp['curve']['b']) . '</' . $pre . 'B>' . "\r\n" . '<' . $pre . 'B>' . Base64::encode($temp['curve']['b']) . '</' . $pre . 'B>' . "\r\n" .

View File

@ -404,7 +404,7 @@ class Hash
if (in_array(substr($hash, 0, 5), ['sha3-', 'shake', 'kecca'])) { if (in_array(substr($hash, 0, 5), ['sha3-', 'shake', 'kecca'])) {
// PHP 7.1.0 introduced support for "SHA3 fixed mode algorithms": // PHP 7.1.0 introduced support for "SHA3 fixed mode algorithms":
// http://php.net/ChangeLog-7.php#7.1.0 // http://php.net/ChangeLog-7.php#7.1.0
if (version_compare(PHP_VERSION, '7.1.0') < 0 || substr($hash, 0,5) != 'sha3-') { if (version_compare(PHP_VERSION, '7.1.0') < 0 || substr($hash, 0, 5) != 'sha3-') {
//preg_match('#(\d+)$#', $hash, $matches); //preg_match('#(\d+)$#', $hash, $matches);
//$this->parameters['capacity'] = 2 * $matches[1]; // 1600 - $this->blockSize //$this->parameters['capacity'] = 2 * $matches[1]; // 1600 - $this->blockSize
//$this->parameters['rate'] = 1600 - $this->parameters['capacity']; // == $this->blockSize //$this->parameters['rate'] = 1600 - $this->parameters['capacity']; // == $this->blockSize
@ -554,7 +554,7 @@ class Hash
$a = self::L1Hash($L1Key_i, $m); $a = self::L1Hash($L1Key_i, $m);
$b = strlen($m) <= 1024 ? "\0\0\0\0\0\0\0\0$a" : self::L2Hash($L2Key_i, $a); $b = strlen($m) <= 1024 ? "\0\0\0\0\0\0\0\0$a" : self::L2Hash($L2Key_i, $a);
$c = self::L3Hash($L3Key1_i, $L3Key2_i, $b); $c = self::L3Hash($L3Key1_i, $L3Key2_i, $b);
$y.= $c; $y .= $c;
} }
return $y; return $y;
@ -586,7 +586,7 @@ class Hash
$y = ''; $y = '';
for ($i = 0; $i < count($m) - 1; $i++) { for ($i = 0; $i < count($m) - 1; $i++) {
$m[$i] = pack('N*', ...unpack('V*', $m[$i])); // ENDIAN-SWAP $m[$i] = pack('N*', ...unpack('V*', $m[$i])); // ENDIAN-SWAP
$y.= static::nh($k, $m[$i], $length); $y .= static::nh($k, $m[$i], $length);
} }
// //
@ -599,7 +599,7 @@ class Hash
$m[$i] = str_pad($m[$i], $pad, "\0"); // zeropad $m[$i] = str_pad($m[$i], $pad, "\0"); // zeropad
$m[$i] = pack('N*', ...unpack('V*', $m[$i])); // ENDIAN-SWAP $m[$i] = pack('N*', ...unpack('V*', $m[$i])); // ENDIAN-SWAP
$y.= static::nh($k, $m[$i], new BigInteger($length * 8)); $y .= static::nh($k, $m[$i], new BigInteger($length * 8));
return $y; return $y;
} }
@ -613,7 +613,7 @@ class Hash
*/ */
private static function nh($k, $m, $length) private static function nh($k, $m, $length)
{ {
$toUInt32 = function($x) { $toUInt32 = function ($x) {
$x = new BigInteger($x, 256); $x = new BigInteger($x, 256);
$x->setPrecision(32); $x->setPrecision(32);
return $x; return $x;
@ -635,7 +635,7 @@ class Hash
// Perform NH hash on the chunks, pairing words for multiplication // Perform NH hash on the chunks, pairing words for multiplication
// which are 4 apart to accommodate vector-parallelism. // which are 4 apart to accommodate vector-parallelism.
// //
$y = new BigInteger; $y = new BigInteger();
$y->setPrecision(64); $y->setPrecision(64);
$i = 0; $i = 0;
while ($i < $t) { while ($i < $t) {
@ -659,7 +659,7 @@ class Hash
$temp = $temp->multiply($m[$i + 7]->add($k[$i + 7])); $temp = $temp->multiply($m[$i + 7]->add($k[$i + 7]));
$y = $y->add($temp); $y = $y->add($temp);
$i+= 8; $i += 8;
} }
return $y->add($length)->toBytes(); return $y->add($length)->toBytes();
@ -702,7 +702,7 @@ class Hash
$m_2 = substr($m, 0x20000) . "\x80"; $m_2 = substr($m, 0x20000) . "\x80";
$length = strlen($m_2); $length = strlen($m_2);
$pad = 16 - ($length % 16); $pad = 16 - ($length % 16);
$pad%= 16; $pad %= 16;
$m_2 = str_pad($m_2, $length + $pad, "\0"); // zeropad $m_2 = str_pad($m_2, $length + $pad, "\0"); // zeropad
$y = self::poly(64, self::$maxwordrange64, $k64, $m_1); $y = self::poly(64, self::$maxwordrange64, $k64, $m_1);
$y = str_pad($y, 16, "\0", STR_PAD_LEFT); $y = str_pad($y, 16, "\0", STR_PAD_LEFT);
@ -863,7 +863,7 @@ class Hash
$temp .= $text; $temp .= $text;
$temp = substr($algo($temp, ...array_values($this->parameters)), 0, $this->length); $temp = substr($algo($temp, ...array_values($this->parameters)), 0, $this->length);
$output = $this->opad ^ $key; $output = $this->opad ^ $key;
$output.= $temp; $output .= $temp;
$output = $algo($output, ...array_values($this->parameters)); $output = $algo($output, ...array_values($this->parameters));
return substr($output, 0, $this->length); return substr($output, 0, $this->length);
@ -981,7 +981,7 @@ class Hash
$padLength = $block_size - (strlen($p) % $block_size); $padLength = $block_size - (strlen($p) % $block_size);
$num_ints = $block_size >> 2; $num_ints = $block_size >> 2;
$p.= static::sha3_pad($padLength, $padType); $p .= static::sha3_pad($padLength, $padType);
$n = strlen($p) / $r; // number of blocks $n = strlen($p) / $r; // number of blocks
@ -998,9 +998,9 @@ class Hash
foreach ($p as $pi) { foreach ($p as $pi) {
$pi = unpack('V*', $pi); $pi = unpack('V*', $pi);
$x = $y = 0; $x = $y = 0;
for ($i = 1; $i <= $num_ints; $i+=2) { for ($i = 1; $i <= $num_ints; $i += 2) {
$s[$x][$y][0]^= $pi[$i + 1]; $s[$x][$y][0] ^= $pi[$i + 1];
$s[$x][$y][1]^= $pi[$i]; $s[$x][$y][1] ^= $pi[$i];
if (++$y == 5) { if (++$y == 5) {
$y = 0; $y = 0;
$x++; $x++;
@ -1012,7 +1012,7 @@ class Hash
$z = ''; $z = '';
$i = $j = 0; $i = $j = 0;
while (strlen($z) < $d) { while (strlen($z) < $d) {
$z.= pack('V2', $s[$i][$j][1], $s[$i][$j++][0]); $z .= pack('V2', $s[$i][$j][1], $s[$i][$j++][0]);
if ($j == 5) { if ($j == 5) {
$j = 0; $j = 0;
$i++; $i++;
@ -1092,8 +1092,8 @@ class Hash
]; ];
for ($i = 0; $i < 5; $i++) { for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) { for ($j = 0; $j < 5; $j++) {
$s[$i][$j][0]^= $temp[$j][0]; $s[$i][$j][0] ^= $temp[$j][0];
$s[$i][$j][1]^= $temp[$j][1]; $s[$i][$j][1] ^= $temp[$j][1];
} }
} }
@ -1131,8 +1131,8 @@ class Hash
} }
// iota step // iota step
$s[0][0][0]^= $roundConstants[$round][0]; $s[0][0][0] ^= $roundConstants[$round][0];
$s[0][0][1]^= $roundConstants[$round][1]; $s[0][0][1] ^= $roundConstants[$round][1];
} }
} }
@ -1148,7 +1148,7 @@ class Hash
if ($shift < 32) { if ($shift < 32) {
list($hi, $lo) = $x; list($hi, $lo) = $x;
} else { } else {
$shift-= 32; $shift -= 32;
list($lo, $hi) = $x; list($lo, $hi) = $x;
} }
@ -1174,7 +1174,7 @@ class Hash
$padLength = $block_size - (strlen($p) % $block_size); $padLength = $block_size - (strlen($p) % $block_size);
$num_ints = $block_size >> 2; $num_ints = $block_size >> 2;
$p.= static::sha3_pad($padLength, $padType); $p .= static::sha3_pad($padLength, $padType);
$n = strlen($p) / $r; // number of blocks $n = strlen($p) / $r; // number of blocks
@ -1192,7 +1192,7 @@ class Hash
$pi = unpack('P*', $pi); $pi = unpack('P*', $pi);
$x = $y = 0; $x = $y = 0;
foreach ($pi as $subpi) { foreach ($pi as $subpi) {
$s[$x][$y++]^= $subpi; $s[$x][$y++] ^= $subpi;
if ($y == 5) { if ($y == 5) {
$y = 0; $y = 0;
$x++; $x++;
@ -1204,7 +1204,7 @@ class Hash
$z = ''; $z = '';
$i = $j = 0; $i = $j = 0;
while (strlen($z) < $d) { while (strlen($z) < $d) {
$z.= pack('P', $s[$i][$j++]); $z .= pack('P', $s[$i][$j++]);
if ($j == 5) { if ($j == 5) {
$j = 0; $j = 0;
$i++; $i++;
@ -1276,7 +1276,7 @@ class Hash
]; ];
for ($i = 0; $i < 5; $i++) { for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) { for ($j = 0; $j < 5; $j++) {
$s[$i][$j]^= $temp[$j]; $s[$i][$j] ^= $temp[$j];
} }
} }
@ -1301,7 +1301,7 @@ class Hash
} }
// iota step // iota step
$s[0][0]^= $roundConstants[$round]; $s[0][0] ^= $roundConstants[$round];
} }
} }
@ -1363,10 +1363,10 @@ class Hash
// Pre-processing // Pre-processing
$length = strlen($m); $length = strlen($m);
// to round to nearest 112 mod 128, we'll add 128 - (length + (128 - 112)) % 128 // to round to nearest 112 mod 128, we'll add 128 - (length + (128 - 112)) % 128
$m.= str_repeat(chr(0), 128 - (($length + 16) & 0x7F)); $m .= str_repeat(chr(0), 128 - (($length + 16) & 0x7F));
$m[$length] = chr(0x80); $m[$length] = chr(0x80);
// we don't support hashing strings 512MB long // we don't support hashing strings 512MB long
$m.= pack('N4', 0, 0, 0, $length << 3); $m .= pack('N4', 0, 0, 0, $length << 3);
// Process the message in successive 1024-bit chunks // Process the message in successive 1024-bit chunks
$chunks = str_split($m, 128); $chunks = str_split($m, 128);

View File

@ -42,15 +42,18 @@ abstract class PublicKeyLoader
{ {
try { try {
return EC::load($key, $password); return EC::load($key, $password);
} catch (NoKeyLoadedException $e) {} } catch (NoKeyLoadedException $e) {
}
try { try {
return RSA::load($key, $password); return RSA::load($key, $password);
} catch (NoKeyLoadedException $e) {} } catch (NoKeyLoadedException $e) {
}
try { try {
return DSA::load($key, $password); return DSA::load($key, $password);
} catch (NoKeyLoadedException $e) {} } catch (NoKeyLoadedException $e) {
}
try { try {
$x509 = new X509(); $x509 = new X509();
@ -59,7 +62,8 @@ abstract class PublicKeyLoader
if ($key) { if ($key) {
return $key; return $key;
} }
} catch (\Exception $e) {} } catch (\Exception $e) {
}
throw new NoKeyLoadedException('Unable to read key'); throw new NoKeyLoadedException('Unable to read key');
} }

View File

@ -425,7 +425,7 @@ abstract class RSA extends AsymmetricKey
// coefficient INTEGER, -- (inverse of q) mod p // coefficient INTEGER, -- (inverse of q) mod p
// otherPrimeInfos OtherPrimeInfos OPTIONAL // otherPrimeInfos OtherPrimeInfos OPTIONAL
// } // }
$privatekey = new PrivateKey; $privatekey = new PrivateKey();
$privatekey->modulus = $n; $privatekey->modulus = $n;
$privatekey->k = $bits >> 3; $privatekey->k = $bits >> 3;
$privatekey->publicExponent = $e; $privatekey->publicExponent = $e;
@ -456,8 +456,8 @@ abstract class RSA extends AsymmetricKey
protected static function onLoad($components) protected static function onLoad($components)
{ {
$key = $components['isPublicKey'] ? $key = $components['isPublicKey'] ?
new PublicKey : new PublicKey() :
new PrivateKey; new PrivateKey();
$key->modulus = $components['modulus']; $key->modulus = $components['modulus'];
$key->publicExponent = $components['publicExponent']; $key->publicExponent = $components['publicExponent'];
@ -603,7 +603,7 @@ abstract class RSA extends AsymmetricKey
case 'sha512/256': case 'sha512/256':
$t = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x06\x05\x00\x04\x20"; $t = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x06\x05\x00\x04\x20";
} }
$t.= $h; $t .= $h;
$tLen = strlen($t); $tLen = strlen($t);
if ($emLen < $tLen + 11) { if ($emLen < $tLen + 11) {
@ -663,7 +663,7 @@ abstract class RSA extends AsymmetricKey
default: default:
throw new UnsupportedAlgorithmException('md2 and md5 require NULLs'); throw new UnsupportedAlgorithmException('md2 and md5 require NULLs');
} }
$t.= $h; $t .= $h;
$tLen = strlen($t); $tLen = strlen($t);
if ($emLen < $tLen + 11) { if ($emLen < $tLen + 11) {
@ -695,7 +695,7 @@ abstract class RSA extends AsymmetricKey
$count = ceil($maskLen / $this->mgfHLen); $count = ceil($maskLen / $this->mgfHLen);
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
$c = pack('N', $i); $c = pack('N', $i);
$t.= $this->mgfHash->hash($mgfSeed . $c); $t .= $this->mgfHash->hash($mgfSeed . $c);
} }
return substr($t, 0, $maskLen); return substr($t, 0, $maskLen);

View File

@ -209,14 +209,14 @@ abstract class MSBLOB
$n = strrev($n->toBytes()); $n = strrev($n->toBytes());
$e = str_pad(strrev($e->toBytes()), 4, "\0"); $e = str_pad(strrev($e->toBytes()), 4, "\0");
$key = pack('aavV', chr(self::PRIVATEKEYBLOB), chr(2), 0, self::CALG_RSA_KEYX); $key = pack('aavV', chr(self::PRIVATEKEYBLOB), chr(2), 0, self::CALG_RSA_KEYX);
$key.= pack('VVa*', self::RSA2, 8 * strlen($n), $e); $key .= pack('VVa*', self::RSA2, 8 * strlen($n), $e);
$key.= $n; $key .= $n;
$key.= strrev($primes[1]->toBytes()); $key .= strrev($primes[1]->toBytes());
$key.= strrev($primes[2]->toBytes()); $key .= strrev($primes[2]->toBytes());
$key.= strrev($exponents[1]->toBytes()); $key .= strrev($exponents[1]->toBytes());
$key.= strrev($exponents[2]->toBytes()); $key .= strrev($exponents[2]->toBytes());
$key.= strrev($coefficients[2]->toBytes()); $key .= strrev($coefficients[2]->toBytes());
$key.= strrev($d->toBytes()); $key .= strrev($d->toBytes());
return Base64::encode($key); return Base64::encode($key);
} }
@ -234,8 +234,8 @@ abstract class MSBLOB
$n = strrev($n->toBytes()); $n = strrev($n->toBytes());
$e = str_pad(strrev($e->toBytes()), 4, "\0"); $e = str_pad(strrev($e->toBytes()), 4, "\0");
$key = pack('aavV', chr(self::PUBLICKEYBLOB), chr(2), 0, self::CALG_RSA_KEYX); $key = pack('aavV', chr(self::PUBLICKEYBLOB), chr(2), 0, self::CALG_RSA_KEYX);
$key.= pack('VVa*', self::RSA1, 8 * strlen($n), $e); $key .= pack('VVa*', self::RSA1, 8 * strlen($n), $e);
$key.= $n; $key .= $n;
return Base64::encode($key); return Base64::encode($key);
} }

View File

@ -70,7 +70,7 @@ abstract class PKCS1 extends Progenitor
$key = ASN1::asn1map($decoded[0], Maps\RSAPrivateKey::MAP); $key = ASN1::asn1map($decoded[0], Maps\RSAPrivateKey::MAP);
if (is_array($key)) { if (is_array($key)) {
$components+= [ $components += [
'modulus' => $key['modulus'], 'modulus' => $key['modulus'],
'publicExponent' => $key['publicExponent'], 'publicExponent' => $key['publicExponent'],
'privateExponent' => $key['privateExponent'], 'privateExponent' => $key['privateExponent'],

View File

@ -74,7 +74,7 @@ abstract class Raw
if (isset($key['primes'])) { if (isset($key['primes'])) {
$components['primes'] = $key['primes']; $components['primes'] = $key['primes'];
} else if (isset($key['p']) && isset($key['q'])) { } elseif (isset($key['p']) && isset($key['q'])) {
$indices = [ $indices = [
['p', 'q'], ['p', 'q'],
['prime1', 'prime2'] ['prime1', 'prime2']
@ -164,9 +164,15 @@ abstract class Raw
'e' => clone $e, 'e' => clone $e,
'n' => clone $n, 'n' => clone $n,
'd' => clone $d, 'd' => clone $d,
'primes' => array_map(function($var) { return clone $var; }, $primes), 'primes' => array_map(function ($var) {
'exponents' => array_map(function($var) { return clone $var; }, $exponents), return clone $var;
'coefficients' => array_map(function($var) { return clone $var; }, $coefficients) }, $primes),
'exponents' => array_map(function ($var) {
return clone $var;
}, $exponents),
'coefficients' => array_map(function ($var) {
return clone $var;
}, $coefficients)
]; ];
} }

View File

@ -408,9 +408,9 @@ class PrivateKey extends RSA implements Common\PrivateKey
$patternMatch = 0; $patternMatch = 0;
$offset = 0; $offset = 0;
for ($i = 0; $i < strlen($m); $i++) { for ($i = 0; $i < strlen($m); $i++) {
$patternMatch|= $leadingZeros & ($m[$i] === "\1"); $patternMatch |= $leadingZeros & ($m[$i] === "\1");
$leadingZeros&= $m[$i] === "\0"; $leadingZeros &= $m[$i] === "\0";
$offset+= $patternMatch ? 0 : 1; $offset += $patternMatch ? 0 : 1;
} }
// we do | instead of || to avoid https://en.wikipedia.org/wiki/Short-circuit_evaluation // we do | instead of || to avoid https://en.wikipedia.org/wiki/Short-circuit_evaluation
@ -505,7 +505,7 @@ class PrivateKey extends RSA implements Common\PrivateKey
if ($type == PSS::class) { if ($type == PSS::class) {
if ($this->signaturePadding == self::SIGNATURE_PSS) { if ($this->signaturePadding == self::SIGNATURE_PSS) {
$options+= [ $options += [
'hash' => $this->hash->getHash(), 'hash' => $this->hash->getHash(),
'MGFHash' => $this->mgfHash->getHash(), 'MGFHash' => $this->mgfHash->getHash(),
'saltLength' => $this->getSaltLength() 'saltLength' => $this->getSaltLength()

View File

@ -349,7 +349,7 @@ class PublicKey extends RSA implements Common\PublicKey
while (strlen($ps) != $psLen) { while (strlen($ps) != $psLen) {
$temp = Random::string($psLen - strlen($ps)); $temp = Random::string($psLen - strlen($ps));
$temp = str_replace("\x00", '', $temp); $temp = str_replace("\x00", '', $temp);
$ps.= $temp; $ps .= $temp;
} }
$type = 2; $type = 2;
$em = chr(0) . chr($type) . $ps . chr(0) . $m; $em = chr(0) . chr($type) . $ps . chr(0) . $m;
@ -492,7 +492,7 @@ class PublicKey extends RSA implements Common\PublicKey
if ($type == PSS::class) { if ($type == PSS::class) {
if ($this->signaturePadding == self::SIGNATURE_PSS) { if ($this->signaturePadding == self::SIGNATURE_PSS) {
$options+= [ $options += [
'hash' => $this->hash->getHash(), 'hash' => $this->hash->getHash(),
'MGFHash' => $this->mgfHash->getHash(), 'MGFHash' => $this->mgfHash->getHash(),
'saltLength' => $this->getSaltLength() 'saltLength' => $this->getSaltLength()
@ -512,7 +512,7 @@ class PublicKey extends RSA implements Common\PublicKey
*/ */
public function asPrivateKey() public function asPrivateKey()
{ {
$new = new PrivateKey; $new = new PrivateKey();
$new->exponent = $this->exponent; $new->exponent = $this->exponent;
$new->modulus = $this->modulus; $new->modulus = $this->modulus;
$new->k = $this->k; $new->k = $this->k;

View File

@ -184,7 +184,7 @@ abstract class Random
$i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21 $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
$r = $crypto->encrypt($i ^ $v); // strlen($v) == 20 $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
$v = $crypto->encrypt($r ^ $i); // strlen($r) == 20 $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
$result.= $r; $result .= $r;
} }
return substr($result, 0, $length); return substr($result, 0, $length);

View File

@ -55,7 +55,6 @@
namespace phpseclib3\Crypt; namespace phpseclib3\Crypt;
use phpseclib3\Common\Functions\Strings; use phpseclib3\Common\Functions\Strings;
use phpseclib3\Crypt\Common\BlockCipher; use phpseclib3\Crypt\Common\BlockCipher;
use phpseclib3\Exception\BadDecryptionException; use phpseclib3\Exception\BadDecryptionException;
use phpseclib3\Exception\BadModeException; use phpseclib3\Exception\BadModeException;
@ -854,7 +853,7 @@ class Rijndael extends BlockCipher
$c = $this->c; $c = $this->c;
// Generating encrypt code: // Generating encrypt code:
$init_encrypt.= ' $init_encrypt .= '
static $tables; static $tables;
if (empty($tables)) { if (empty($tables)) {
$tables = &$this->getTables(); $tables = &$this->getTables();
@ -871,47 +870,47 @@ class Rijndael extends BlockCipher
$wc = $Nb - 1; $wc = $Nb - 1;
// Preround: addRoundKey // Preround: addRoundKey
$encrypt_block = '$in = unpack("N*", $in);'."\n"; $encrypt_block = '$in = unpack("N*", $in);' . "\n";
for ($i = 0; $i < $Nb; ++$i) { for ($i = 0; $i < $Nb; ++$i) {
$encrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$w[++$wc].";\n"; $encrypt_block .= '$s' . $i . ' = $in[' . ($i + 1) . '] ^ ' . $w[++$wc] . ";\n";
} }
// Mainrounds: shiftRows + subWord + mixColumns + addRoundKey // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey
for ($round = 1; $round < $Nr; ++$round) { for ($round = 1; $round < $Nr; ++$round) {
list($s, $e) = [$e, $s]; list($s, $e) = [$e, $s];
for ($i = 0; $i < $Nb; ++$i) { for ($i = 0; $i < $Nb; ++$i) {
$encrypt_block.= $encrypt_block .=
'$'.$e.$i.' = '$' . $e . $i . ' =
$t0[($'.$s.$i .' >> 24) & 0xff] ^ $t0[($' . $s . $i . ' >> 24) & 0xff] ^
$t1[($'.$s.(($i + $c[1]) % $Nb).' >> 16) & 0xff] ^ $t1[($' . $s . (($i + $c[1]) % $Nb) . ' >> 16) & 0xff] ^
$t2[($'.$s.(($i + $c[2]) % $Nb).' >> 8) & 0xff] ^ $t2[($' . $s . (($i + $c[2]) % $Nb) . ' >> 8) & 0xff] ^
$t3[ $'.$s.(($i + $c[3]) % $Nb).' & 0xff] ^ $t3[ $' . $s . (($i + $c[3]) % $Nb) . ' & 0xff] ^
'.$w[++$wc].";\n"; ' . $w[++$wc] . ";\n";
} }
} }
// Finalround: subWord + shiftRows + addRoundKey // Finalround: subWord + shiftRows + addRoundKey
for ($i = 0; $i < $Nb; ++$i) { for ($i = 0; $i < $Nb; ++$i) {
$encrypt_block.= $encrypt_block .=
'$'.$e.$i.' = '$' . $e . $i . ' =
$sbox[ $'.$e.$i.' & 0xff] | $sbox[ $' . $e . $i . ' & 0xff] |
($sbox[($'.$e.$i.' >> 8) & 0xff] << 8) | ($sbox[($' . $e . $i . ' >> 8) & 0xff] << 8) |
($sbox[($'.$e.$i.' >> 16) & 0xff] << 16) | ($sbox[($' . $e . $i . ' >> 16) & 0xff] << 16) |
($sbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n"; ($sbox[($' . $e . $i . ' >> 24) & 0xff] << 24);' . "\n";
} }
$encrypt_block .= '$in = pack("N*"'."\n"; $encrypt_block .= '$in = pack("N*"' . "\n";
for ($i = 0; $i < $Nb; ++$i) { for ($i = 0; $i < $Nb; ++$i) {
$encrypt_block.= ', $encrypt_block .= ',
($'.$e.$i .' & '.((int)0xFF000000).') ^ ($' . $e . $i . ' & ' . ((int)0xFF000000) . ') ^
($'.$e.(($i + $c[1]) % $Nb).' & 0x00FF0000 ) ^ ($' . $e . (($i + $c[1]) % $Nb) . ' & 0x00FF0000 ) ^
($'.$e.(($i + $c[2]) % $Nb).' & 0x0000FF00 ) ^ ($' . $e . (($i + $c[2]) % $Nb) . ' & 0x0000FF00 ) ^
($'.$e.(($i + $c[3]) % $Nb).' & 0x000000FF ) ^ ($' . $e . (($i + $c[3]) % $Nb) . ' & 0x000000FF ) ^
'.$w[$i]."\n"; ' . $w[$i] . "\n";
} }
$encrypt_block .= ');'; $encrypt_block .= ');';
// Generating decrypt code: // Generating decrypt code:
$init_decrypt.= ' $init_decrypt .= '
static $invtables; static $invtables;
if (empty($invtables)) { if (empty($invtables)) {
$invtables = &$this->getInvTables(); $invtables = &$this->getInvTables();
@ -928,42 +927,42 @@ class Rijndael extends BlockCipher
$wc = $Nb - 1; $wc = $Nb - 1;
// Preround: addRoundKey // Preround: addRoundKey
$decrypt_block = '$in = unpack("N*", $in);'."\n"; $decrypt_block = '$in = unpack("N*", $in);' . "\n";
for ($i = 0; $i < $Nb; ++$i) { for ($i = 0; $i < $Nb; ++$i) {
$decrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$dw[++$wc].';'."\n"; $decrypt_block .= '$s' . $i . ' = $in[' . ($i + 1) . '] ^ ' . $dw[++$wc] . ';' . "\n";
} }
// Mainrounds: shiftRows + subWord + mixColumns + addRoundKey // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey
for ($round = 1; $round < $Nr; ++$round) { for ($round = 1; $round < $Nr; ++$round) {
list($s, $e) = [$e, $s]; list($s, $e) = [$e, $s];
for ($i = 0; $i < $Nb; ++$i) { for ($i = 0; $i < $Nb; ++$i) {
$decrypt_block.= $decrypt_block .=
'$'.$e.$i.' = '$' . $e . $i . ' =
$dt0[($'.$s.$i .' >> 24) & 0xff] ^ $dt0[($' . $s . $i . ' >> 24) & 0xff] ^
$dt1[($'.$s.(($Nb + $i - $c[1]) % $Nb).' >> 16) & 0xff] ^ $dt1[($' . $s . (($Nb + $i - $c[1]) % $Nb) . ' >> 16) & 0xff] ^
$dt2[($'.$s.(($Nb + $i - $c[2]) % $Nb).' >> 8) & 0xff] ^ $dt2[($' . $s . (($Nb + $i - $c[2]) % $Nb) . ' >> 8) & 0xff] ^
$dt3[ $'.$s.(($Nb + $i - $c[3]) % $Nb).' & 0xff] ^ $dt3[ $' . $s . (($Nb + $i - $c[3]) % $Nb) . ' & 0xff] ^
'.$dw[++$wc].";\n"; ' . $dw[++$wc] . ";\n";
} }
} }
// Finalround: subWord + shiftRows + addRoundKey // Finalround: subWord + shiftRows + addRoundKey
for ($i = 0; $i < $Nb; ++$i) { for ($i = 0; $i < $Nb; ++$i) {
$decrypt_block.= $decrypt_block .=
'$'.$e.$i.' = '$' . $e . $i . ' =
$isbox[ $'.$e.$i.' & 0xff] | $isbox[ $' . $e . $i . ' & 0xff] |
($isbox[($'.$e.$i.' >> 8) & 0xff] << 8) | ($isbox[($' . $e . $i . ' >> 8) & 0xff] << 8) |
($isbox[($'.$e.$i.' >> 16) & 0xff] << 16) | ($isbox[($' . $e . $i . ' >> 16) & 0xff] << 16) |
($isbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n"; ($isbox[($' . $e . $i . ' >> 24) & 0xff] << 24);' . "\n";
} }
$decrypt_block .= '$in = pack("N*"'."\n"; $decrypt_block .= '$in = pack("N*"' . "\n";
for ($i = 0; $i < $Nb; ++$i) { for ($i = 0; $i < $Nb; ++$i) {
$decrypt_block.= ', $decrypt_block .= ',
($'.$e.$i. ' & '.((int)0xFF000000).') ^ ($' . $e . $i . ' & ' . ((int)0xFF000000) . ') ^
($'.$e.(($Nb + $i - $c[1]) % $Nb).' & 0x00FF0000 ) ^ ($' . $e . (($Nb + $i - $c[1]) % $Nb) . ' & 0x00FF0000 ) ^
($'.$e.(($Nb + $i - $c[2]) % $Nb).' & 0x0000FF00 ) ^ ($' . $e . (($Nb + $i - $c[2]) % $Nb) . ' & 0x0000FF00 ) ^
($'.$e.(($Nb + $i - $c[3]) % $Nb).' & 0x000000FF ) ^ ($' . $e . (($Nb + $i - $c[3]) % $Nb) . ' & 0x000000FF ) ^
'.$dw[$i]."\n"; ' . $dw[$i] . "\n";
} }
$decrypt_block .= ');'; $decrypt_block .= ');';

View File

@ -216,7 +216,7 @@ class Salsa20 extends StreamCipher
$key = $this->key; $key = $this->key;
if (strlen($key) == 16) { if (strlen($key) == 16) {
$constant = 'expand 16-byte k'; $constant = 'expand 16-byte k';
$key.= $key; $key .= $key;
} else { } else {
$constant = 'expand 32-byte k'; $constant = 'expand 32-byte k';
} }
@ -330,7 +330,7 @@ class Salsa20 extends StreamCipher
$i = $this->counter; $i = $this->counter;
$blocks = str_split($text, 64); $blocks = str_split($text, 64);
foreach ($blocks as &$block) { foreach ($blocks as &$block) {
$block^= static::salsa20($this->p1 . pack('V', $i++) . $this->p2); $block ^= static::salsa20($this->p1 . pack('V', $i++) . $this->p2);
} }
return implode('', $blocks); return implode('', $blocks);
@ -357,7 +357,7 @@ class Salsa20 extends StreamCipher
if ($this->engine == self::ENGINE_OPENSSL) { if ($this->engine == self::ENGINE_OPENSSL) {
$iv = pack('V', $buffer['counter']) . $this->p2; $iv = pack('V', $buffer['counter']) . $this->p2;
// at this point $text should be a multiple of 64 // at this point $text should be a multiple of 64
$buffer['counter']+= (strlen($text) >> 6) + 1; // ie. divide by 64 $buffer['counter'] += (strlen($text) >> 6) + 1; // ie. divide by 64
$encrypted = openssl_encrypt( $encrypted = openssl_encrypt(
$text . str_repeat("\0", 64), $text . str_repeat("\0", 64),
$this->cipher_name_openssl, $this->cipher_name_openssl,
@ -370,19 +370,19 @@ class Salsa20 extends StreamCipher
$blocks = str_split($text, 64); $blocks = str_split($text, 64);
if (strlen($text)) { if (strlen($text)) {
foreach ($blocks as &$block) { foreach ($blocks as &$block) {
$block^= static::salsa20($this->p1 . pack('V', $buffer['counter']++) . $this->p2); $block ^= static::salsa20($this->p1 . pack('V', $buffer['counter']++) . $this->p2);
} }
} }
$encrypted = implode('', $blocks); $encrypted = implode('', $blocks);
$temp = static::salsa20($this->p1 . pack('V', $buffer['counter']++) . $this->p2); $temp = static::salsa20($this->p1 . pack('V', $buffer['counter']++) . $this->p2);
} }
$ciphertext.= $encrypted . ($text2 ^ $temp); $ciphertext .= $encrypted . ($text2 ^ $temp);
$buffer['ciphertext'] = substr($temp, $overflow); $buffer['ciphertext'] = substr($temp, $overflow);
} elseif (!strlen($buffer['ciphertext'])) { } elseif (!strlen($buffer['ciphertext'])) {
if ($this->engine == self::ENGINE_OPENSSL) { if ($this->engine == self::ENGINE_OPENSSL) {
$iv = pack('V', $buffer['counter']) . $this->p2; $iv = pack('V', $buffer['counter']) . $this->p2;
$buffer['counter']+= (strlen($text) >> 6); $buffer['counter'] += (strlen($text) >> 6);
$ciphertext.= openssl_encrypt( $ciphertext .= openssl_encrypt(
$text, $text,
$this->cipher_name_openssl, $this->cipher_name_openssl,
$this->key, $this->key,
@ -392,9 +392,9 @@ class Salsa20 extends StreamCipher
} else { } else {
$blocks = str_split($text, 64); $blocks = str_split($text, 64);
foreach ($blocks as &$block) { foreach ($blocks as &$block) {
$block^= static::salsa20($this->p1 . pack('V', $buffer['counter']++) . $this->p2); $block ^= static::salsa20($this->p1 . pack('V', $buffer['counter']++) . $this->p2);
} }
$ciphertext.= implode('', $blocks); $ciphertext .= implode('', $blocks);
} }
} }
@ -412,11 +412,11 @@ class Salsa20 extends StreamCipher
{ {
$r1 = $x << $n; $r1 = $x << $n;
if (PHP_INT_SIZE == 8) { if (PHP_INT_SIZE == 8) {
$r1&= 0xFFFFFFFF; $r1 &= 0xFFFFFFFF;
$r2 = ($x & 0xFFFFFFFF) >> (32 - $n); $r2 = ($x & 0xFFFFFFFF) >> (32 - $n);
} else { } else {
$r2 = $x >> (32 - $n); $r2 = $x >> (32 - $n);
$r2&= (1 << $n) - 1; $r2 &= (1 << $n) - 1;
} }
return $r1 | $r2; return $r1 | $r2;
} }
@ -431,10 +431,10 @@ class Salsa20 extends StreamCipher
*/ */
protected static function quarterRound(&$a, &$b, &$c, &$d) protected static function quarterRound(&$a, &$b, &$c, &$d)
{ {
$b^= self::leftRotate($a + $d, 7); $b ^= self::leftRotate($a + $d, 7);
$c^= self::leftRotate($b + $a, 9); $c ^= self::leftRotate($b + $a, 9);
$d^= self::leftRotate($c + $b, 13); $d ^= self::leftRotate($c + $b, 13);
$a^= self::leftRotate($d + $c, 18); $a ^= self::leftRotate($d + $c, 18);
} }
/** /**
@ -460,13 +460,13 @@ class Salsa20 extends StreamCipher
protected static function doubleRound(&$x0, &$x1, &$x2, &$x3, &$x4, &$x5, &$x6, &$x7, &$x8, &$x9, &$x10, &$x11, &$x12, &$x13, &$x14, &$x15) protected static function doubleRound(&$x0, &$x1, &$x2, &$x3, &$x4, &$x5, &$x6, &$x7, &$x8, &$x9, &$x10, &$x11, &$x12, &$x13, &$x14, &$x15)
{ {
// columnRound // columnRound
static::quarterRound( $x0, $x4, $x8, $x12); static::quarterRound($x0, $x4, $x8, $x12);
static::quarterRound( $x5, $x9, $x13, $x1); static::quarterRound($x5, $x9, $x13, $x1);
static::quarterRound($x10, $x14, $x2, $x6); static::quarterRound($x10, $x14, $x2, $x6);
static::quarterRound($x15, $x3, $x7, $x11); static::quarterRound($x15, $x3, $x7, $x11);
// rowRound // rowRound
static::quarterRound( $x0, $x1, $x2, $x3); static::quarterRound($x0, $x1, $x2, $x3);
static::quarterRound( $x5, $x6, $x7, $x4); static::quarterRound($x5, $x6, $x7, $x4);
static::quarterRound($x10, $x11, $x8, $x9); static::quarterRound($x10, $x11, $x8, $x9);
static::quarterRound($x15, $x12, $x13, $x14); static::quarterRound($x15, $x12, $x13, $x14);
} }
@ -484,7 +484,7 @@ class Salsa20 extends StreamCipher
} }
for ($i = 1; $i <= 16; $i++) { for ($i = 1; $i <= 16; $i++) {
$x[$i]+= $z[$i]; $x[$i] += $z[$i];
} }
return pack('V*', ...$x); return pack('V*', ...$x);

View File

@ -260,7 +260,7 @@ class TripleDES extends DES
switch (strlen($key)) { switch (strlen($key)) {
case 16: case 16:
$key.= substr($key, 0, 8); $key .= substr($key, 0, 8);
break; break;
case 24: case 24:
break; break;

View File

@ -463,7 +463,7 @@ class Twofish extends BlockCipher
case 16: case 16:
list($s7, $s6, $s5, $s4) = $this->mdsrem($le_longs[1], $le_longs[2]); list($s7, $s6, $s5, $s4) = $this->mdsrem($le_longs[1], $le_longs[2]);
list($s3, $s2, $s1, $s0) = $this->mdsrem($le_longs[3], $le_longs[4]); list($s3, $s2, $s1, $s0) = $this->mdsrem($le_longs[3], $le_longs[4]);
for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { for ($i = 0, $j = 1; $i < 40; $i += 2, $j += 2) {
$A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^ $A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^
$m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^ $m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^
$m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^ $m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^
@ -489,7 +489,7 @@ class Twofish extends BlockCipher
list($sb, $sa, $s9, $s8) = $this->mdsrem($le_longs[1], $le_longs[2]); list($sb, $sa, $s9, $s8) = $this->mdsrem($le_longs[1], $le_longs[2]);
list($s7, $s6, $s5, $s4) = $this->mdsrem($le_longs[3], $le_longs[4]); list($s7, $s6, $s5, $s4) = $this->mdsrem($le_longs[3], $le_longs[4]);
list($s3, $s2, $s1, $s0) = $this->mdsrem($le_longs[5], $le_longs[6]); list($s3, $s2, $s1, $s0) = $this->mdsrem($le_longs[5], $le_longs[6]);
for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { for ($i = 0, $j = 1; $i < 40; $i += 2, $j += 2) {
$A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ $A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^
$m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ $m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^
$m2[$q1[$q0[$q0[$i] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^ $m2[$q1[$q0[$q0[$i] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^
@ -516,7 +516,7 @@ class Twofish extends BlockCipher
list($sb, $sa, $s9, $s8) = $this->mdsrem($le_longs[3], $le_longs[4]); list($sb, $sa, $s9, $s8) = $this->mdsrem($le_longs[3], $le_longs[4]);
list($s7, $s6, $s5, $s4) = $this->mdsrem($le_longs[5], $le_longs[6]); list($s7, $s6, $s5, $s4) = $this->mdsrem($le_longs[5], $le_longs[6]);
list($s3, $s2, $s1, $s0) = $this->mdsrem($le_longs[7], $le_longs[8]); list($s3, $s2, $s1, $s0) = $this->mdsrem($le_longs[7], $le_longs[8]);
for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { for ($i = 0, $j = 1; $i < 40; $i += 2, $j += 2) {
$A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ $A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^
$m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ $m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^
$m2[$q1[$q0[$q0[$q0[$i] ^ $key[27]] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^ $m2[$q1[$q0[$q0[$q0[$i] ^ $key[27]] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^
@ -563,28 +563,28 @@ class Twofish extends BlockCipher
// Shift the others up. // Shift the others up.
$B = ($B << 8) | (0xff & ($A >> 24)); $B = ($B << 8) | (0xff & ($A >> 24));
$A<<= 8; $A <<= 8;
$u = $t << 1; $u = $t << 1;
// Subtract the modular polynomial on overflow. // Subtract the modular polynomial on overflow.
if ($t & 0x80) { if ($t & 0x80) {
$u^= 0x14d; $u ^= 0x14d;
} }
// Remove t * (a * x^2 + 1). // Remove t * (a * x^2 + 1).
$B ^= $t ^ ($u << 16); $B ^= $t ^ ($u << 16);
// Form u = a*t + t/a = t*(a + 1/a). // Form u = a*t + t/a = t*(a + 1/a).
$u^= 0x7fffffff & ($t >> 1); $u ^= 0x7fffffff & ($t >> 1);
// Add the modular polynomial on underflow. // Add the modular polynomial on underflow.
if ($t & 0x01) { if ($t & 0x01) {
$u^= 0xa6 ; $u ^= 0xa6 ;
} }
// Remove t * (a + 1/a) * (x^3 + x). // Remove t * (a + 1/a) * (x^3 + x).
$B^= ($u << 24) | ($u << 8); $B ^= ($u << 24) | ($u << 8);
} }
return [ return [
@ -625,7 +625,7 @@ class Twofish extends BlockCipher
$S1[ $R1 & 0xff] ^ $S1[ $R1 & 0xff] ^
$S2[($R1 >> 8) & 0xff] ^ $S2[($R1 >> 8) & 0xff] ^
$S3[($R1 >> 16) & 0xff]; $S3[($R1 >> 16) & 0xff];
$R2^= self::safe_intval($t0 + $t1 + $K[++$ki]); $R2 ^= self::safe_intval($t0 + $t1 + $K[++$ki]);
$R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31); $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31);
$R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ self::safe_intval($t0 + ($t1 << 1) + $K[++$ki]); $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ self::safe_intval($t0 + ($t1 << 1) + $K[++$ki]);
@ -637,7 +637,7 @@ class Twofish extends BlockCipher
$S1[ $R3 & 0xff] ^ $S1[ $R3 & 0xff] ^
$S2[($R3 >> 8) & 0xff] ^ $S2[($R3 >> 8) & 0xff] ^
$S3[($R3 >> 16) & 0xff]; $S3[($R3 >> 16) & 0xff];
$R0^= self::safe_intval($t0 + $t1 + $K[++$ki]); $R0 ^= self::safe_intval($t0 + $t1 + $K[++$ki]);
$R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31); $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31);
$R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ self::safe_intval($t0 + ($t1 << 1) + $K[++$ki]); $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ self::safe_intval($t0 + ($t1 << 1) + $K[++$ki]);
} }
@ -681,7 +681,7 @@ class Twofish extends BlockCipher
$S1[$R1 & 0xff] ^ $S1[$R1 & 0xff] ^
$S2[$R1 >> 8 & 0xff] ^ $S2[$R1 >> 8 & 0xff] ^
$S3[$R1 >> 16 & 0xff]; $S3[$R1 >> 16 & 0xff];
$R3^= self::safe_intval($t0 + ($t1 << 1) + $K[--$ki]); $R3 ^= self::safe_intval($t0 + ($t1 << 1) + $K[--$ki]);
$R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31; $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31;
$R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ self::safe_intval($t0 + $t1 + $K[--$ki]); $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ self::safe_intval($t0 + $t1 + $K[--$ki]);
@ -693,7 +693,7 @@ class Twofish extends BlockCipher
$S1[$R3 & 0xff] ^ $S1[$R3 & 0xff] ^
$S2[$R3 >> 8 & 0xff] ^ $S2[$R3 >> 8 & 0xff] ^
$S3[$R3 >> 16 & 0xff]; $S3[$R3 >> 16 & 0xff];
$R1^= self::safe_intval($t0 + ($t1 << 1) + $K[--$ki]); $R1 ^= self::safe_intval($t0 + ($t1 << 1) + $K[--$ki]);
$R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31; $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31;
$R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ self::safe_intval($t0 + $t1 + $K[--$ki]); $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ self::safe_intval($t0 + $t1 + $K[--$ki]);
} }
@ -732,13 +732,13 @@ class Twofish extends BlockCipher
// Generating encrypt code: // Generating encrypt code:
$encrypt_block = ' $encrypt_block = '
$in = unpack("V4", $in); $in = unpack("V4", $in);
$R0 = '.$K[0].' ^ $in[1]; $R0 = ' . $K[0] . ' ^ $in[1];
$R1 = '.$K[1].' ^ $in[2]; $R1 = ' . $K[1] . ' ^ $in[2];
$R2 = '.$K[2].' ^ $in[3]; $R2 = ' . $K[2] . ' ^ $in[3];
$R3 = '.$K[3].' ^ $in[4]; $R3 = ' . $K[3] . ' ^ $in[4];
'; ';
for ($ki = 7, $i = 0; $i < 8; ++$i) { for ($ki = 7, $i = 0; $i < 8; ++$i) {
$encrypt_block.= ' $encrypt_block .= '
$t0 = $S0[ $R0 & 0xff] ^ $t0 = $S0[ $R0 & 0xff] ^
$S1[($R0 >> 8) & 0xff] ^ $S1[($R0 >> 8) & 0xff] ^
$S2[($R0 >> 16) & 0xff] ^ $S2[($R0 >> 16) & 0xff] ^
@ -764,23 +764,23 @@ class Twofish extends BlockCipher
$R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ' . sprintf($safeint, '($t0 + ($t1 << 1) + ' . $K[++$ki] . ')') . '; $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ' . sprintf($safeint, '($t0 + ($t1 << 1) + ' . $K[++$ki] . ')') . ';
'; ';
} }
$encrypt_block.= ' $encrypt_block .= '
$in = pack("V4", '.$K[4].' ^ $R2, $in = pack("V4", ' . $K[4] . ' ^ $R2,
'.$K[5].' ^ $R3, ' . $K[5] . ' ^ $R3,
'.$K[6].' ^ $R0, ' . $K[6] . ' ^ $R0,
'.$K[7].' ^ $R1); ' . $K[7] . ' ^ $R1);
'; ';
// Generating decrypt code: // Generating decrypt code:
$decrypt_block = ' $decrypt_block = '
$in = unpack("V4", $in); $in = unpack("V4", $in);
$R0 = '.$K[4].' ^ $in[1]; $R0 = ' . $K[4] . ' ^ $in[1];
$R1 = '.$K[5].' ^ $in[2]; $R1 = ' . $K[5] . ' ^ $in[2];
$R2 = '.$K[6].' ^ $in[3]; $R2 = ' . $K[6] . ' ^ $in[3];
$R3 = '.$K[7].' ^ $in[4]; $R3 = ' . $K[7] . ' ^ $in[4];
'; ';
for ($ki = 40, $i = 0; $i < 8; ++$i) { for ($ki = 40, $i = 0; $i < 8; ++$i) {
$decrypt_block.= ' $decrypt_block .= '
$t0 = $S0[$R0 & 0xff] ^ $t0 = $S0[$R0 & 0xff] ^
$S1[$R0 >> 8 & 0xff] ^ $S1[$R0 >> 8 & 0xff] ^
$S2[$R0 >> 16 & 0xff] ^ $S2[$R0 >> 16 & 0xff] ^
@ -791,7 +791,7 @@ class Twofish extends BlockCipher
$S3[$R1 >> 16 & 0xff]; $S3[$R1 >> 16 & 0xff];
$R3^= ' . sprintf($safeint, '$t0 + ($t1 << 1) + ' . $K[--$ki]) . '; $R3^= ' . sprintf($safeint, '$t0 + ($t1 << 1) + ' . $K[--$ki]) . ';
$R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31; $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31;
$R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ' . sprintf($safeint, '($t0 + $t1 + '.$K[--$ki] . ')') . '; $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ' . sprintf($safeint, '($t0 + $t1 + ' . $K[--$ki] . ')') . ';
$t0 = $S0[$R2 & 0xff] ^ $t0 = $S0[$R2 & 0xff] ^
$S1[$R2 >> 8 & 0xff] ^ $S1[$R2 >> 8 & 0xff] ^
@ -803,14 +803,14 @@ class Twofish extends BlockCipher
$S3[$R3 >> 16 & 0xff]; $S3[$R3 >> 16 & 0xff];
$R1^= ' . sprintf($safeint, '$t0 + ($t1 << 1) + ' . $K[--$ki]) . '; $R1^= ' . sprintf($safeint, '$t0 + ($t1 << 1) + ' . $K[--$ki]) . ';
$R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31; $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31;
$R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ' . sprintf($safeint, '($t0 + $t1 + '.$K[--$ki] . ')') . '; $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ' . sprintf($safeint, '($t0 + $t1 + ' . $K[--$ki] . ')') . ';
'; ';
} }
$decrypt_block.= ' $decrypt_block .= '
$in = pack("V4", '.$K[0].' ^ $R2, $in = pack("V4", ' . $K[0] . ' ^ $R2,
'.$K[1].' ^ $R3, ' . $K[1] . ' ^ $R3,
'.$K[2].' ^ $R0, ' . $K[2] . ' ^ $R0,
'.$K[3].' ^ $R1); ' . $K[3] . ' ^ $R1);
'; ';
$this->inline_crypt = $this->createInlineCryptFunction( $this->inline_crypt = $this->createInlineCryptFunction(

View File

@ -234,7 +234,7 @@ class ANSI
$this->tokenization = ['']; $this->tokenization = [''];
for ($i = 0; $i < strlen($source); $i++) { for ($i = 0; $i < strlen($source); $i++) {
if (strlen($this->ansi)) { if (strlen($this->ansi)) {
$this->ansi.= $source[$i]; $this->ansi .= $source[$i];
$chr = ord($source[$i]); $chr = ord($source[$i]);
// http://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements // http://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements
// single character CSI's not currently supported // single character CSI's not currently supported
@ -299,11 +299,11 @@ class ANSI
break; break;
case preg_match('#\x1B\[(\d+)C#', $this->ansi, $match): // Move cursor right n lines case preg_match('#\x1B\[(\d+)C#', $this->ansi, $match): // Move cursor right n lines
$this->old_x = $this->x; $this->old_x = $this->x;
$this->x+= $match[1]; $this->x += $match[1];
break; break;
case preg_match('#\x1B\[(\d+)D#', $this->ansi, $match): // Move cursor left n lines case preg_match('#\x1B\[(\d+)D#', $this->ansi, $match): // Move cursor left n lines
$this->old_x = $this->x; $this->old_x = $this->x;
$this->x-= $match[1]; $this->x -= $match[1];
if ($this->x < 0) { if ($this->x < 0) {
$this->x = 0; $this->x = 0;
} }
@ -376,7 +376,7 @@ class ANSI
continue; continue;
} }
$this->tokenization[count($this->tokenization) - 1].= $source[$i]; $this->tokenization[count($this->tokenization) - 1] .= $source[$i];
switch ($source[$i]) { switch ($source[$i]) {
case "\r": case "\r":
$this->x = 0; $this->x = 0;
@ -403,7 +403,7 @@ class ANSI
//if (!strlen($this->tokenization[count($this->tokenization) - 1])) { //if (!strlen($this->tokenization[count($this->tokenization) - 1])) {
// array_pop($this->tokenization); // array_pop($this->tokenization);
//} //}
$this->ansi.= "\x1B"; $this->ansi .= "\x1B";
break; break;
default: default:
$this->attrs[$this->y][$this->x] = clone $this->attr_cell; $this->attrs[$this->y][$this->x] = clone $this->attr_cell;
@ -474,7 +474,7 @@ class ANSI
$close = $open = ''; $close = $open = '';
if ($last_attr->foreground != $cur_attr->foreground) { if ($last_attr->foreground != $cur_attr->foreground) {
if ($cur_attr->foreground != 'white') { if ($cur_attr->foreground != 'white') {
$open.= '<span style="color: ' . $cur_attr->foreground . '">'; $open .= '<span style="color: ' . $cur_attr->foreground . '">';
} }
if ($last_attr->foreground != 'white') { if ($last_attr->foreground != 'white') {
$close = '</span>' . $close; $close = '</span>' . $close;
@ -482,7 +482,7 @@ class ANSI
} }
if ($last_attr->background != $cur_attr->background) { if ($last_attr->background != $cur_attr->background) {
if ($cur_attr->background != 'black') { if ($cur_attr->background != 'black') {
$open.= '<span style="background: ' . $cur_attr->background . '">'; $open .= '<span style="background: ' . $cur_attr->background . '">';
} }
if ($last_attr->background != 'black') { if ($last_attr->background != 'black') {
$close = '</span>' . $close; $close = '</span>' . $close;
@ -490,29 +490,29 @@ class ANSI
} }
if ($last_attr->bold != $cur_attr->bold) { if ($last_attr->bold != $cur_attr->bold) {
if ($cur_attr->bold) { if ($cur_attr->bold) {
$open.= '<b>'; $open .= '<b>';
} else { } else {
$close = '</b>' . $close; $close = '</b>' . $close;
} }
} }
if ($last_attr->underline != $cur_attr->underline) { if ($last_attr->underline != $cur_attr->underline) {
if ($cur_attr->underline) { if ($cur_attr->underline) {
$open.= '<u>'; $open .= '<u>';
} else { } else {
$close = '</u>' . $close; $close = '</u>' . $close;
} }
} }
if ($last_attr->blink != $cur_attr->blink) { if ($last_attr->blink != $cur_attr->blink) {
if ($cur_attr->blink) { if ($cur_attr->blink) {
$open.= '<blink>'; $open .= '<blink>';
} else { } else {
$close = '</blink>' . $close; $close = '</blink>' . $close;
} }
} }
$output.= $close . $open; $output .= $close . $open;
} }
$output.= htmlspecialchars($char); $output .= htmlspecialchars($char);
return $output; return $output;
} }
@ -530,14 +530,14 @@ class ANSI
for ($i = 0; $i <= $this->max_y; $i++) { for ($i = 0; $i <= $this->max_y; $i++) {
for ($j = 0; $j <= $this->max_x; $j++) { for ($j = 0; $j <= $this->max_x; $j++) {
$cur_attr = $this->attrs[$i][$j]; $cur_attr = $this->attrs[$i][$j];
$output.= $this->processCoordinate($last_attr, $cur_attr, isset($this->screen[$i][$j]) ? $this->screen[$i][$j] : ''); $output .= $this->processCoordinate($last_attr, $cur_attr, isset($this->screen[$i][$j]) ? $this->screen[$i][$j] : '');
$last_attr = $this->attrs[$i][$j]; $last_attr = $this->attrs[$i][$j];
} }
$output.= "\r\n"; $output .= "\r\n";
} }
$output = substr($output, 0, -2); $output = substr($output, 0, -2);
// close any remaining open tags // close any remaining open tags
$output.= $this->processCoordinate($last_attr, $this->base_attr_cell, ''); $output .= $this->processCoordinate($last_attr, $this->base_attr_cell, '');
return rtrim($output); return rtrim($output);
} }
@ -565,14 +565,14 @@ class ANSI
for ($i = 0; $i < count($this->history); $i++) { for ($i = 0; $i < count($this->history); $i++) {
for ($j = 0; $j <= $this->max_x + 1; $j++) { for ($j = 0; $j <= $this->max_x + 1; $j++) {
$cur_attr = $this->history_attrs[$i][$j]; $cur_attr = $this->history_attrs[$i][$j];
$scrollback.= $this->processCoordinate($last_attr, $cur_attr, isset($this->history[$i][$j]) ? $this->history[$i][$j] : ''); $scrollback .= $this->processCoordinate($last_attr, $cur_attr, isset($this->history[$i][$j]) ? $this->history[$i][$j] : '');
$last_attr = $this->history_attrs[$i][$j]; $last_attr = $this->history_attrs[$i][$j];
} }
$scrollback.= "\r\n"; $scrollback .= "\r\n";
} }
$base_attr_cell = $this->base_attr_cell; $base_attr_cell = $this->base_attr_cell;
$this->base_attr_cell = $last_attr; $this->base_attr_cell = $last_attr;
$scrollback.= $this->getScreen(); $scrollback .= $this->getScreen();
$this->base_attr_cell = $base_attr_cell; $this->base_attr_cell = $base_attr_cell;
return '<pre width="' . ($this->max_x + 1) . '" style="color: white; background: black">' . $scrollback . '</span></pre>'; return '<pre width="' . ($this->max_x + 1) . '" style="color: white; background: black">' . $scrollback . '</span></pre>';

View File

@ -266,7 +266,7 @@ abstract class ASN1
} while ($loop); } while ($loop);
} }
$start+= $startOffset; $start += $startOffset;
// Length, as discussed in paragraph 8.1.3 of X.690-0207.pdf#page=13 // Length, as discussed in paragraph 8.1.3 of X.690-0207.pdf#page=13
if (!isset($encoded[$encoded_pos])) { if (!isset($encoded[$encoded_pos])) {
@ -281,16 +281,16 @@ abstract class ASN1
} elseif ($length & 0x80) { // definite length, long form } elseif ($length & 0x80) { // definite length, long form
// technically, the long form of the length can be represented by up to 126 octets (bytes), but we'll only // technically, the long form of the length can be represented by up to 126 octets (bytes), but we'll only
// support it up to four. // support it up to four.
$length&= 0x7F; $length &= 0x7F;
$temp = substr($encoded, $encoded_pos, $length); $temp = substr($encoded, $encoded_pos, $length);
$encoded_pos += $length; $encoded_pos += $length;
// tags of indefinte length don't really have a header length; this length includes the tag // tags of indefinte length don't really have a header length; this length includes the tag
$current+= ['headerlength' => $length + 2]; $current += ['headerlength' => $length + 2];
$start+= $length; $start += $length;
extract(unpack('Nlength', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4))); extract(unpack('Nlength', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)));
/** @var integer $length */ /** @var integer $length */
} else { } else {
$current+= ['headerlength' => 2]; $current += ['headerlength' => 2];
} }
if ($length > (strlen($encoded) - $encoded_pos)) { if ($length > (strlen($encoded) - $encoded_pos)) {
@ -335,13 +335,13 @@ abstract class ASN1
$length = $temp['length']; $length = $temp['length'];
// end-of-content octets - see paragraph 8.1.5 // end-of-content octets - see paragraph 8.1.5
if (substr($content, $content_pos + $length, 2) == "\0\0") { if (substr($content, $content_pos + $length, 2) == "\0\0") {
$length+= 2; $length += 2;
$start+= $length; $start += $length;
$newcontent[] = $temp; $newcontent[] = $temp;
break; break;
} }
$start+= $length; $start += $length;
$remainingLength-= $length; $remainingLength -= $length;
$newcontent[] = $temp; $newcontent[] = $temp;
$content_pos += $length; $content_pos += $length;
} }
@ -358,7 +358,7 @@ abstract class ASN1
] + $current; ] + $current;
} }
$current+= ['type' => $tag]; $current += ['type' => $tag];
// decode UNIVERSAL tags // decode UNIVERSAL tags
switch ($tag) { switch ($tag) {
@ -389,14 +389,14 @@ abstract class ASN1
if ($temp === false) { if ($temp === false) {
return false; return false;
} }
$length-= (strlen($content) - $content_pos); $length -= (strlen($content) - $content_pos);
$last = count($temp) - 1; $last = count($temp) - 1;
for ($i = 0; $i < $last; $i++) { for ($i = 0; $i < $last; $i++) {
// all subtags should be bit strings // all subtags should be bit strings
if ($temp[$i]['type'] != self::TYPE_BIT_STRING) { if ($temp[$i]['type'] != self::TYPE_BIT_STRING) {
return false; return false;
} }
$current['content'].= substr($temp[$i]['content'], 1); $current['content'] .= substr($temp[$i]['content'], 1);
} }
// all subtags should be bit strings // all subtags should be bit strings
if ($temp[$last]['type'] != self::TYPE_BIT_STRING) { if ($temp[$last]['type'] != self::TYPE_BIT_STRING) {
@ -421,11 +421,11 @@ abstract class ASN1
if ($temp['type'] != self::TYPE_OCTET_STRING) { if ($temp['type'] != self::TYPE_OCTET_STRING) {
return false; return false;
} }
$current['content'].= $temp['content']; $current['content'] .= $temp['content'];
$length+= $temp['length']; $length += $temp['length'];
} }
if (substr($content, $content_pos, 2) == "\0\0") { if (substr($content, $content_pos, 2) == "\0\0") {
$length+= 2; // +2 for the EOC $length += 2; // +2 for the EOC
} }
} }
break; break;
@ -456,7 +456,7 @@ abstract class ASN1
} }
$content_pos += $temp['length']; $content_pos += $temp['length'];
$current['content'][] = $temp; $current['content'][] = $temp;
$offset+= $temp['length']; $offset += $temp['length'];
} }
break; break;
case self::TYPE_OBJECT_IDENTIFIER: case self::TYPE_OBJECT_IDENTIFIER:
@ -512,7 +512,7 @@ abstract class ASN1
return false; return false;
} }
$start+= $length; $start += $length;
// ie. length is the length of the full TLV encoding - it's not just the length of the value // ie. length is the length of the full TLV encoding - it's not just the length of the value
return $current + ['length' => $start - $current['start']]; return $current + ['length' => $start - $current['start']];
@ -664,7 +664,7 @@ abstract class ASN1
} }
// Fail mapping if all input items have not been consumed. // Fail mapping if all input items have not been consumed.
return $i < $n ? null: $map; return $i < $n ? null : $map;
// the main diff between sets and sequences is the encapsulation of the foreach in another for loop // the main diff between sets and sequences is the encapsulation of the foreach in another for loop
case self::TYPE_SET: case self::TYPE_SET:
@ -834,7 +834,7 @@ abstract class ASN1
{ {
$length = ord(Strings::shift($string)); $length = ord(Strings::shift($string));
if ($length & 0x80) { // definite length, long form if ($length & 0x80) { // definite length, long form
$length&= 0x7F; $length &= 0x7F;
$temp = Strings::shift($string, $length); $temp = Strings::shift($string, $length);
list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)); list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
} }
@ -894,7 +894,7 @@ abstract class ASN1
switch ($tag) { switch ($tag) {
case self::TYPE_SET: // Children order is not important, thus process in sequence. case self::TYPE_SET: // Children order is not important, thus process in sequence.
case self::TYPE_SEQUENCE: case self::TYPE_SEQUENCE:
$tag|= 0x20; // set the constructed bit $tag |= 0x20; // set the constructed bit
// ignore the min and max // ignore the min and max
if (isset($mapping['min']) && isset($mapping['max'])) { if (isset($mapping['min']) && isset($mapping['max'])) {
@ -906,7 +906,7 @@ abstract class ASN1
if ($temp === false) { if ($temp === false) {
return false; return false;
} }
$value[]= $temp; $value[] = $temp;
} }
/* "The encodings of the component values of a set-of value shall appear in ascending order, the encodings being compared /* "The encodings of the component values of a set-of value shall appear in ascending order, the encodings being compared
as octet strings with the shorter components being padded at their trailing end with 0-octets. as octet strings with the shorter components being padded at their trailing end with 0-octets.
@ -959,7 +959,7 @@ abstract class ASN1
$temp = $subtag . substr($temp, 1); $temp = $subtag . substr($temp, 1);
} }
} }
$value.= $temp; $value .= $temp;
} }
break; break;
case self::TYPE_CHOICE: case self::TYPE_CHOICE:
@ -1026,7 +1026,7 @@ abstract class ASN1
case self::TYPE_UTC_TIME: case self::TYPE_UTC_TIME:
case self::TYPE_GENERALIZED_TIME: case self::TYPE_GENERALIZED_TIME:
$format = $mapping['type'] == self::TYPE_UTC_TIME ? 'y' : 'Y'; $format = $mapping['type'] == self::TYPE_UTC_TIME ? 'y' : 'Y';
$format.= 'mdHis'; $format .= 'mdHis';
// if $source does _not_ include timezone information within it then assume that the timezone is GMT // if $source does _not_ include timezone information within it then assume that the timezone is GMT
$date = new \DateTime($source, new \DateTimeZone('GMT')); $date = new \DateTime($source, new \DateTimeZone('GMT'));
// if $source _does_ include timezone information within it then convert the time to GMT // if $source _does_ include timezone information within it then convert the time to GMT
@ -1060,7 +1060,7 @@ abstract class ASN1
$bits = implode('', array_pad($bits, $size + $offset + 1, 0)); $bits = implode('', array_pad($bits, $size + $offset + 1, 0));
$bytes = explode(' ', rtrim(chunk_split($bits, 8, ' '))); $bytes = explode(' ', rtrim(chunk_split($bits, 8, ' ')));
foreach ($bytes as $byte) { foreach ($bytes as $byte) {
$value.= chr(bindec($byte)); $value .= chr(bindec($byte));
} }
break; break;
@ -1255,7 +1255,7 @@ abstract class ASN1
} }
$temp[strlen($temp) - 1] = $temp[strlen($temp) - 1] & chr(0x7F); $temp[strlen($temp) - 1] = $temp[strlen($temp) - 1] & chr(0x7F);
} }
$value.= $temp; $value .= $temp;
} }
return $value; return $value;
@ -1293,7 +1293,7 @@ abstract class ASN1
$prefix = substr($content, 0, 2) >= 50 ? '19' : '20'; $prefix = substr($content, 0, 2) >= 50 ? '19' : '20';
$content = $prefix . $content; $content = $prefix . $content;
} elseif (strpos($content, '.') !== false) { } elseif (strpos($content, '.') !== false) {
$format.= '.u'; $format .= '.u';
} }
if ($content[strlen($content) - 1] == 'Z') { if ($content[strlen($content) - 1] == 'Z') {
@ -1301,7 +1301,7 @@ abstract class ASN1
} }
if (strpos($content, '-') !== false || strpos($content, '+') !== false) { if (strpos($content, '-') !== false || strpos($content, '+') !== false) {
$format.= 'O'; $format .= 'O';
} }
// error supression isn't necessary as of PHP 7.0: // error supression isn't necessary as of PHP 7.0:
@ -1333,7 +1333,7 @@ abstract class ASN1
*/ */
public static function loadOIDs($oids) public static function loadOIDs($oids)
{ {
self::$reverseOIDs+= $oids; self::$reverseOIDs += $oids;
self::$oids = array_flip(self::$reverseOIDs); self::$oids = array_flip(self::$reverseOIDs);
} }

View File

@ -30,7 +30,7 @@ abstract class Attribute
'type' => ASN1::TYPE_SEQUENCE, 'type' => ASN1::TYPE_SEQUENCE,
'children' => [ 'children' => [
'type' => AttributeType::MAP, 'type' => AttributeType::MAP,
'value'=> [ 'value' => [
'type' => ASN1::TYPE_SET, 'type' => ASN1::TYPE_SET,
'min' => 1, 'min' => 1,
'max' => -1, 'max' => -1,

View File

@ -30,7 +30,7 @@ abstract class AttributeTypeAndValue
'type' => ASN1::TYPE_SEQUENCE, 'type' => ASN1::TYPE_SEQUENCE,
'children' => [ 'children' => [
'type' => AttributeType::MAP, 'type' => AttributeType::MAP,
'value'=> AttributeValue::MAP 'value' => AttributeValue::MAP
] ]
]; ];
} }

View File

@ -60,7 +60,7 @@ abstract class IssuingDistributionPoint
'default' => false, 'default' => false,
'implicit' => true 'implicit' => true
], ],
'onlyContainsAttributeCerts' =>[ 'onlyContainsAttributeCerts' => [
'type' => ASN1::TYPE_BOOLEAN, 'type' => ASN1::TYPE_BOOLEAN,
'constant' => 5, 'constant' => 5,
'optional' => true, 'optional' => true,

View File

@ -35,7 +35,7 @@ abstract class OneAsymmetricKey
'type' => ASN1::TYPE_INTEGER, 'type' => ASN1::TYPE_INTEGER,
'mapping' => ['v1', 'v2'] 'mapping' => ['v1', 'v2']
], ],
'privateKeyAlgorithm'=> AlgorithmIdentifier::MAP, 'privateKeyAlgorithm' => AlgorithmIdentifier::MAP,
'privateKey' => PrivateKey::MAP, 'privateKey' => PrivateKey::MAP,
'attributes' => [ 'attributes' => [
'constant' => 0, 'constant' => 0,

View File

@ -31,7 +31,7 @@ abstract class PBES2params
const MAP = [ const MAP = [
'type' => ASN1::TYPE_SEQUENCE, 'type' => ASN1::TYPE_SEQUENCE,
'children' => [ 'children' => [
'keyDerivationFunc'=> AlgorithmIdentifier::MAP, 'keyDerivationFunc' => AlgorithmIdentifier::MAP,
'encryptionScheme' => AlgorithmIdentifier::MAP 'encryptionScheme' => AlgorithmIdentifier::MAP
] ]
]; ];

View File

@ -33,8 +33,8 @@ abstract class PBKDF2params
'children' => [ 'children' => [
// technically, this is a CHOICE in RFC2898 but the other "choice" is, currently, more of a placeholder // technically, this is a CHOICE in RFC2898 but the other "choice" is, currently, more of a placeholder
// in the RFC // in the RFC
'salt'=> ['type' => ASN1::TYPE_OCTET_STRING], 'salt' => ['type' => ASN1::TYPE_OCTET_STRING],
'iterationCount'=> ['type' => ASN1::TYPE_INTEGER], 'iterationCount' => ['type' => ASN1::TYPE_INTEGER],
'keyLength' => [ 'keyLength' => [
'type' => ASN1::TYPE_INTEGER, 'type' => ASN1::TYPE_INTEGER,
'optional' => true 'optional' => true

View File

@ -31,8 +31,8 @@ abstract class PBMAC1params
const MAP = [ const MAP = [
'type' => ASN1::TYPE_SEQUENCE, 'type' => ASN1::TYPE_SEQUENCE,
'children' => [ 'children' => [
'keyDerivationFunc'=> AlgorithmIdentifier::MAP, 'keyDerivationFunc' => AlgorithmIdentifier::MAP,
'messageAuthScheme'=> AlgorithmIdentifier::MAP 'messageAuthScheme' => AlgorithmIdentifier::MAP
] ]
]; ];
} }

View File

@ -33,7 +33,7 @@ abstract class PrivateKeyInfo
'type' => ASN1::TYPE_INTEGER, 'type' => ASN1::TYPE_INTEGER,
'mapping' => ['v1'] 'mapping' => ['v1']
], ],
'privateKeyAlgorithm'=> AlgorithmIdentifier::MAP, 'privateKeyAlgorithm' => AlgorithmIdentifier::MAP,
'privateKey' => PrivateKey::MAP, 'privateKey' => PrivateKey::MAP,
'attributes' => [ 'attributes' => [
'constant' => 0, 'constant' => 0,

View File

@ -32,7 +32,7 @@ abstract class PublicKeyInfo
const MAP = [ const MAP = [
'type' => ASN1::TYPE_SEQUENCE, 'type' => ASN1::TYPE_SEQUENCE,
'children' => [ 'children' => [
'publicKeyAlgorithm'=> AlgorithmIdentifier::MAP, 'publicKeyAlgorithm' => AlgorithmIdentifier::MAP,
'publicKey' => ['type' => ASN1::TYPE_BIT_STRING] 'publicKey' => ['type' => ASN1::TYPE_BIT_STRING]
] ]
]; ];

View File

@ -31,11 +31,11 @@ abstract class RC2CBCParameter
const MAP = [ const MAP = [
'type' => ASN1::TYPE_SEQUENCE, 'type' => ASN1::TYPE_SEQUENCE,
'children' => [ 'children' => [
'rc2ParametersVersion'=> [ 'rc2ParametersVersion' => [
'type' => ASN1::TYPE_INTEGER, 'type' => ASN1::TYPE_INTEGER,
'optional' => true 'optional' => true
], ],
'iv'=> ['type' => ASN1::TYPE_OCTET_STRING] 'iv' => ['type' => ASN1::TYPE_OCTET_STRING]
] ]
]; ];
} }

View File

@ -334,7 +334,7 @@ class X509
//'id-ad' => '1.3.6.1.5.5.7.48', //'id-ad' => '1.3.6.1.5.5.7.48',
'id-qt-cps' => '1.3.6.1.5.5.7.2.1', 'id-qt-cps' => '1.3.6.1.5.5.7.2.1',
'id-qt-unotice' => '1.3.6.1.5.5.7.2.2', 'id-qt-unotice' => '1.3.6.1.5.5.7.2.2',
'id-ad-ocsp' =>'1.3.6.1.5.5.7.48.1', 'id-ad-ocsp' => '1.3.6.1.5.5.7.48.1',
'id-ad-caIssuers' => '1.3.6.1.5.5.7.48.2', 'id-ad-caIssuers' => '1.3.6.1.5.5.7.48.2',
'id-ad-timeStamping' => '1.3.6.1.5.5.7.48.3', 'id-ad-timeStamping' => '1.3.6.1.5.5.7.48.3',
'id-ad-caRepository' => '1.3.6.1.5.5.7.48.5', 'id-ad-caRepository' => '1.3.6.1.5.5.7.48.5',
@ -1148,7 +1148,7 @@ class X509
$notBefore = new \DateTimeImmutable($notBefore, new \DateTimeZone(@date_default_timezone_get())); $notBefore = new \DateTimeImmutable($notBefore, new \DateTimeZone(@date_default_timezone_get()));
$notAfter = new \DateTimeImmutable($notAfter, new \DateTimeZone(@date_default_timezone_get())); $notAfter = new \DateTimeImmutable($notAfter, new \DateTimeZone(@date_default_timezone_get()));
return $date >= $notBefore && $date<= $notAfter; return $date >= $notBefore && $date <= $notAfter;
} }
/** /**
@ -1192,7 +1192,7 @@ class X509
if ($temp === false) { if ($temp === false) {
return false; return false;
} }
$data.= $temp; $data .= $temp;
} }
break; break;
@ -1694,7 +1694,7 @@ class X509
$this->dn['rdnSequence'][] = [ $this->dn['rdnSequence'][] = [
[ [
'type' => $propName, 'type' => $propName,
'value'=> $v 'value' => $v
] ]
]; ];
} }
@ -1827,7 +1827,7 @@ class X509
// handles everything else // handles everything else
$results = preg_split('#((?:^|, *|/)(?:C=|O=|OU=|CN=|L=|ST=|SN=|postalCode=|streetAddress=|emailAddress=|serialNumber=|organizationalUnitName=|title=|description=|role=|x500UniqueIdentifier=|postalAddress=))#', $dn, -1, PREG_SPLIT_DELIM_CAPTURE); $results = preg_split('#((?:^|, *|/)(?:C=|O=|OU=|CN=|L=|ST=|SN=|postalCode=|streetAddress=|emailAddress=|serialNumber=|organizationalUnitName=|title=|description=|role=|x500UniqueIdentifier=|postalAddress=))#', $dn, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 1; $i < count($results); $i+=2) { for ($i = 1; $i < count($results); $i += 2) {
$prop = trim($results[$i], ', =/'); $prop = trim($results[$i], ', =/');
$value = $results[$i + 1]; $value = $results[$i + 1];
if (!$this->setDNProp($prop, $value, $type)) { if (!$this->setDNProp($prop, $value, $type)) {
@ -1949,7 +1949,7 @@ class X509
} }
if (!$start) { if (!$start) {
$output.= $delim; $output .= $delim;
} }
if (is_array($value)) { if (is_array($value)) {
foreach ($value as $type => $v) { foreach ($value as $type => $v) {
@ -1966,10 +1966,12 @@ class X509
$value = array_pop($value); // Always strip data type. $value = array_pop($value); // Always strip data type.
} }
} elseif (is_object($value) && $value instanceof Element) { } elseif (is_object($value) && $value instanceof Element) {
$callback = function($x) { return '\x' . bin2hex($x[0]); }; $callback = function ($x) {
return '\x' . bin2hex($x[0]);
};
$value = strtoupper(preg_replace_callback('#[^\x20-\x7E]#', $callback, $value->element)); $value = strtoupper(preg_replace_callback('#[^\x20-\x7E]#', $callback, $value->element));
} }
$output.= $desc . '=' . $value; $output .= $desc . '=' . $value;
$result[$desc] = isset($result[$desc]) ? $result[$desc] = isset($result[$desc]) ?
array_merge((array) $result[$desc], [$value]) : array_merge((array) $result[$desc], [$value]) :
$value; $value;
@ -3457,7 +3459,7 @@ class X509
* @access public * @access public
* @return mixed * @return mixed
*/ */
public function getExtension($id, $cert = null, $path=null) public function getExtension($id, $cert = null, $path = null)
{ {
return $this->getExtensionHelper($id, $cert, $path); return $this->getExtensionHelper($id, $cert, $path);
} }
@ -3656,7 +3658,7 @@ class X509
$attributes[$last]['value'][] = $value; $attributes[$last]['value'][] = $value;
break; break;
default: default:
$attributes[] = ['type' => $id, 'value' => $disposition == self::ATTR_ALL ? $value: [$value]]; $attributes[] = ['type' => $id, 'value' => $disposition == self::ATTR_ALL ? $value : [$value]];
break; break;
} }

View File

@ -204,7 +204,7 @@ class BigInteger
*/ */
public function __toString() public function __toString()
{ {
return (string) $this->value; return (string)$this->value;
} }
/** /**
@ -248,7 +248,7 @@ class BigInteger
* @param bool $twos_compliment * @param bool $twos_compliment
* @return string * @return string
*/ */
function toBits($twos_compliment = false) public function toBits($twos_compliment = false)
{ {
return $this->value->toBits($twos_compliment); return $this->value->toBits($twos_compliment);
} }
@ -270,7 +270,7 @@ class BigInteger
* @param BigInteger $y * @param BigInteger $y
* @return BigInteger * @return BigInteger
*/ */
function subtract(BigInteger $y) public function subtract(BigInteger $y)
{ {
return new static($this->value->subtract($y->value)); return new static($this->value->subtract($y->value));
} }
@ -324,8 +324,9 @@ class BigInteger
* Calculates modular inverses. * Calculates modular inverses.
* *
* Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses. * Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses.
* @return BigInteger *
* @param BigInteger $n * @param BigInteger $n
* @return BigInteger
*/ */
public function modInverse(BigInteger $n) public function modInverse(BigInteger $n)
{ {
@ -336,8 +337,9 @@ class BigInteger
* Calculates modular inverses. * Calculates modular inverses.
* *
* Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses. * Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses.
* @return BigInteger[] *
* @param BigInteger $n * @param BigInteger $n
* @return BigInteger[]
*/ */
public function extendedGCD(BigInteger $n) public function extendedGCD(BigInteger $n)
{ {
@ -470,8 +472,8 @@ class BigInteger
/** /**
* Compares two numbers. * Compares two numbers.
* *
* Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this is * Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this
* demonstrated thusly: * is demonstrated thusly:
* *
* $x > $y: $x->compare($y) > 0 * $x > $y: $x->compare($y) > 0
* $x < $y: $x->compare($y) < 0 * $x < $y: $x->compare($y) < 0
@ -754,7 +756,9 @@ class BigInteger
public static function min(BigInteger ...$nums) public static function min(BigInteger ...$nums)
{ {
$class = self::$mainEngine; $class = self::$mainEngine;
$nums = array_map(function($num) { return $num->value; }, $nums); $nums = array_map(function ($num) {
return $num->value;
}, $nums);
return new static($class::min(...$nums)); return new static($class::min(...$nums));
} }
@ -767,7 +771,9 @@ class BigInteger
public static function max(BigInteger ...$nums) public static function max(BigInteger ...$nums)
{ {
$class = self::$mainEngine; $class = self::$mainEngine;
$nums = array_map(function($num) { return $num->value; }, $nums); $nums = array_map(function ($num) {
return $num->value;
}, $nums);
return new static($class::max(...$nums)); return new static($class::max(...$nums));
} }
@ -859,7 +865,7 @@ class BigInteger
public function createRecurringModuloFunction() public function createRecurringModuloFunction()
{ {
$func = $this->value->createRecurringModuloFunction(); $func = $this->value->createRecurringModuloFunction();
return function(BigInteger $x) use ($func) { return function (BigInteger $x) use ($func) {
return new static($func($x->value)); return new static($func($x->value));
}; };
} }
@ -874,7 +880,7 @@ class BigInteger
*/ */
public function bitwise_split($split) public function bitwise_split($split)
{ {
return array_map(function($val) { return array_map(function ($val) {
return new static($val); return new static($val);
}, $this->value->bitwise_split($split)); }, $this->value->bitwise_split($split));
} }

View File

@ -89,8 +89,8 @@ class BCMath extends Engine
/** /**
* Test for engine validity * Test for engine validity
* *
* @see parent::__construct()
* @return bool * @return bool
* @see parent::__construct()
*/ */
public static function isValidEngine() public static function isValidEngine()
{ {
@ -102,8 +102,8 @@ class BCMath extends Engine
* *
* @param mixed $x integer Base-10 number or base-$base number if $base set. * @param mixed $x integer Base-10 number or base-$base number if $base set.
* @param int $base * @param int $base
* @see parent::__construct()
* @return \phpseclib3\Math\BigInteger\Engines\BCMath * @return \phpseclib3\Math\BigInteger\Engines\BCMath
* @see parent::__construct()
*/ */
public function __construct($x = 0, $base = 10) public function __construct($x = 0, $base = 10)
{ {
@ -135,9 +135,15 @@ class BCMath extends Engine
$x = str_pad($this->value, $len, chr(0), STR_PAD_LEFT); $x = str_pad($this->value, $len, chr(0), STR_PAD_LEFT);
$this->value = '0'; $this->value = '0';
for ($i = 0; $i < $len; $i+= 4) { for ($i = 0; $i < $len; $i += 4) {
$this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32 $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32
$this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0); $this->value = bcadd(
$this->value,
0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord(
$x[$i + 2]
) << 8) | ord($x[$i + 3])),
0
);
} }
if ($this->is_negative) { if ($this->is_negative) {
@ -153,7 +159,7 @@ class BCMath extends Engine
case 10: case 10:
// explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different
// results then doing it on '-1' does (modInverse does $x[0]) // results then doing it on '-1' does (modInverse does $x[0])
$this->value = $this->value === '-' ? '0' : (string) $this->value; $this->value = $this->value === '-' ? '0' : (string)$this->value;
} }
} }
@ -177,7 +183,7 @@ class BCMath extends Engine
* @param bool $twos_compliment * @param bool $twos_compliment
* @return string * @return string
*/ */
function toBytes($twos_compliment = false) public function toBytes($twos_compliment = false)
{ {
if ($twos_compliment) { if ($twos_compliment) {
return $this->toBytesHelper(); return $this->toBytesHelper();
@ -274,8 +280,8 @@ class BCMath extends Engine
* *
* Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses. * Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses.
* *
* @return false|BCMath
* @param \phpseclib3\Math\BigInteger\Engines\BCMath $n * @param \phpseclib3\Math\BigInteger\Engines\BCMath $n
* @return false|BCMath
*/ */
public function modInverse(BCMath $n) public function modInverse(BCMath $n)
{ {
@ -428,8 +434,8 @@ class BCMath extends Engine
/** /**
* Compares two numbers. * Compares two numbers.
* *
* Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this is * Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this
* demonstrated thusly: * is demonstrated thusly:
* *
* $x > $y: $x->compare($y) > 0 * $x > $y: $x->compare($y) > 0
* $x < $y: $x->compare($y) < 0 * $x < $y: $x->compare($y) < 0
@ -604,9 +610,9 @@ class BCMath extends Engine
* *
* ie. $s = gmp_scan1($n, 0) and $r = gmp_div_q($n, gmp_pow(gmp_init('2'), $s)); * ie. $s = gmp_scan1($n, 0) and $r = gmp_div_q($n, gmp_pow(gmp_init('2'), $s));
* *
* @see self::isPrime()
* @param BCMath $r * @param BCMath $r
* @return int * @return int
* @see self::isPrime()
*/ */
public static function scan1divide(BCMath $r) public static function scan1divide(BCMath $r)
{ {
@ -672,8 +678,8 @@ class BCMath extends Engine
/** /**
* Set Bitmask * Set Bitmask
* *
* @return Engine
* @param int $bits * @param int $bits
* @return Engine
* @see self::setPrecision() * @see self::setPrecision()
*/ */
protected static function setBitmask($bits) protected static function setBitmask($bits)

View File

@ -92,7 +92,7 @@ abstract class Barrett extends Base
$cache[self::DATA][] = [ $cache[self::DATA][] = [
'u' => $u, // m.length >> 1 (technically (m.length >> 1) + 1) 'u' => $u, // m.length >> 1 (technically (m.length >> 1) + 1)
'm1'=> $m1 // m.length 'm1' => $m1 // m.length
]; ];
} else { } else {
extract($cache[self::DATA][$key]); extract($cache[self::DATA][$key]);

View File

@ -76,9 +76,9 @@ abstract class EvalBarrett extends Base
$m = "'$m'"; $m = "'$m'";
$u = "'$u'"; $u = "'$u'";
$m1= "'$m1'"; $m1 = "'$m1'";
$code.= ' $code .= '
$lsd = substr($n, -' . $cutoff . '); $lsd = substr($n, -' . $cutoff . ');
$msd = substr($n, 0, -' . $cutoff . '); $msd = substr($n, 0, -' . $cutoff . ');

View File

@ -494,9 +494,9 @@ abstract class Engine
} }
if ($shift < 0) { if ($shift < 0) {
$shift+= $precision; $shift += $precision;
} }
$shift%= $precision; $shift %= $precision;
if (!$shift) { if (!$shift) {
return clone $this; return clone $this;
@ -1132,7 +1132,7 @@ abstract class Engine
} }
return [ return [
'gcd'=> $u, 'gcd' => $u,
'x' => $a, 'x' => $a,
'y' => $b 'y' => $b
]; ];

View File

@ -90,8 +90,8 @@ class GMP extends Engine
/** /**
* Test for engine validity * Test for engine validity
* *
* @see parent::__construct()
* @return bool * @return bool
* @see parent::__construct()
*/ */
public static function isValidEngine() public static function isValidEngine()
{ {
@ -103,8 +103,8 @@ class GMP extends Engine
* *
* @param mixed $x integer Base-10 number or base-$base number if $base set. * @param mixed $x integer Base-10 number or base-$base number if $base set.
* @param int $base * @param int $base
* @see parent::__construct()
* @return \phpseclib3\Math\BigInteger\Engines\GMP * @return \phpseclib3\Math\BigInteger\Engines\GMP
* @see parent::__construct()
*/ */
public function __construct($x = 0, $base = 10) public function __construct($x = 0, $base = 10)
{ {
@ -156,7 +156,7 @@ class GMP extends Engine
*/ */
public function toString() public function toString()
{ {
return (string) $this->value; return (string)$this->value;
} }
/** /**
@ -191,7 +191,7 @@ class GMP extends Engine
* @param bool $twos_compliment * @param bool $twos_compliment
* @return string * @return string
*/ */
function toBytes($twos_compliment = false) public function toBytes($twos_compliment = false)
{ {
if ($twos_compliment) { if ($twos_compliment) {
return $this->toBytesHelper(); return $this->toBytesHelper();
@ -278,8 +278,8 @@ class GMP extends Engine
/** /**
* Compares two numbers. * Compares two numbers.
* *
* Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this is * Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this
* demonstrated thusly: * is demonstrated thusly:
* *
* $x > $y: $x->compare($y) > 0 * $x > $y: $x->compare($y) > 0
* $x < $y: $x->compare($y) < 0 * $x < $y: $x->compare($y) < 0
@ -680,7 +680,7 @@ class GMP extends Engine
public function createRecurringModuloFunction() public function createRecurringModuloFunction()
{ {
$temp = $this->value; $temp = $this->value;
return function(GMP $x) use ($temp) { return function (GMP $x) use ($temp) {
return new GMP($x->value % $temp); return new GMP($x->value % $temp);
}; };
} }

View File

@ -76,8 +76,8 @@ abstract class PHP extends Engine
* *
* @param mixed $x integer Base-10 number or base-$base number if $base set. * @param mixed $x integer Base-10 number or base-$base number if $base set.
* @param int $base * @param int $base
* @see parent::__construct()
* @return \phpseclib3\Math\BigInteger\Engines\PHP * @return \phpseclib3\Math\BigInteger\Engines\PHP
* @see parent::__construct()
*/ */
public function __construct($x = 0, $base = 10) public function __construct($x = 0, $base = 10)
{ {
@ -119,7 +119,12 @@ abstract class PHP extends Engine
$x = substr($x, 1); $x = substr($x, 1);
} }
$x = str_pad($x, strlen($x) + ((static::MAX10LEN - 1) * strlen($x)) % static::MAX10LEN, 0, STR_PAD_LEFT); $x = str_pad(
$x,
strlen($x) + ((static::MAX10LEN - 1) * strlen($x)) % static::MAX10LEN,
0,
STR_PAD_LEFT
);
while (strlen($x)) { while (strlen($x)) {
$temp = $temp->multiply($multiplier); $temp = $temp->multiply($multiplier);
$temp = $temp->add(new static($this->int2bytes(substr($x, 0, static::MAX10LEN)), 256)); $temp = $temp->add(new static($this->int2bytes(substr($x, 0, static::MAX10LEN)), 256));
@ -165,7 +170,12 @@ abstract class PHP extends Engine
$result = ''; $result = '';
while (count($temp->value)) { while (count($temp->value)) {
list($temp, $mod) = $temp->divide($divisor); list($temp, $mod) = $temp->divide($divisor);
$result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', static::MAX10LEN, '0', STR_PAD_LEFT) . $result; $result = str_pad(
isset($mod->value[0]) ? $mod->value[0] : '',
static::MAX10LEN,
'0',
STR_PAD_LEFT
) . $result;
} }
$result = ltrim($result, '0'); $result = ltrim($result, '0');
if (empty($result)) { if (empty($result)) {
@ -199,7 +209,12 @@ abstract class PHP extends Engine
$result = implode('', array_map('chr', $result)); $result = implode('', array_map('chr', $result));
return $this->precision > 0 ? return $this->precision > 0 ?
str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) : str_pad(
substr($result, -(($this->precision + 7) >> 3)),
($this->precision + 7) >> 3,
chr(0),
STR_PAD_LEFT
) :
$result; $result;
} }
@ -256,7 +271,7 @@ abstract class PHP extends Engine
$value[count($value)] = 0; // just in case the carry adds an extra digit $value[count($value)] = 0; // just in case the carry adds an extra digit
$carry = 0; $carry = 0;
for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) { for ($i = 0, $j = 1; $j < $size; $i += 2, $j += 2) {
//$sum = $x_value[$j] * static::BASE_FULL + $x_value[$i] + $y_value[$j] * static::BASE_FULL + $y_value[$i] + $carry; //$sum = $x_value[$j] * static::BASE_FULL + $x_value[$i] + $y_value[$j] * static::BASE_FULL + $y_value[$i] + $carry;
$sum = ($x_value[$j] + $y_value[$j]) * static::BASE_FULL + $x_value[$i] + $y_value[$i] + $carry; $sum = ($x_value[$j] + $y_value[$j]) * static::BASE_FULL + $x_value[$i] + $y_value[$i] + $carry;
$carry = $sum >= static::MAX_DIGIT2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1 $carry = $sum >= static::MAX_DIGIT2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
@ -264,7 +279,7 @@ abstract class PHP extends Engine
$temp = static::BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31); $temp = static::BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31);
$value[$i] = (int) ($sum - static::BASE_FULL * $temp); // eg. a faster alternative to fmod($sum, 0x4000000) $value[$i] = (int)($sum - static::BASE_FULL * $temp); // eg. a faster alternative to fmod($sum, 0x4000000)
$value[$j] = $temp; $value[$j] = $temp;
} }
@ -297,7 +312,7 @@ abstract class PHP extends Engine
* @param bool $y_negative * @param bool $y_negative
* @return array * @return array
*/ */
static function subtractHelper(array $x_value, $x_negative, array $y_value, $y_negative) public static function subtractHelper(array $x_value, $x_negative, array $y_value, $y_negative)
{ {
$x_size = count($x_value); $x_size = count($x_value);
$y_size = count($y_value); $y_size = count($y_value);
@ -346,7 +361,7 @@ abstract class PHP extends Engine
// at this point, $x_value should be at least as big as - if not bigger than - $y_value // at this point, $x_value should be at least as big as - if not bigger than - $y_value
$carry = 0; $carry = 0;
for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) { for ($i = 0, $j = 1; $j < $y_size; $i += 2, $j += 2) {
$sum = ($x_value[$j] - $y_value[$j]) * static::BASE_FULL + $x_value[$i] - $y_value[$i] - $carry; $sum = ($x_value[$j] - $y_value[$j]) * static::BASE_FULL + $x_value[$i] - $y_value[$i] - $carry;
$carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1 $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
@ -354,7 +369,7 @@ abstract class PHP extends Engine
$temp = static::BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31); $temp = static::BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31);
$x_value[$i] = (int) ($sum - static::BASE_FULL * $temp); $x_value[$i] = (int)($sum - static::BASE_FULL * $temp);
$x_value[$j] = $temp; $x_value[$j] = $temp;
} }
@ -485,7 +500,7 @@ abstract class PHP extends Engine
for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0 for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0
$temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0 $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
$carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
$product_value[$j] = (int) ($temp - static::BASE_FULL * $carry); $product_value[$j] = (int)($temp - static::BASE_FULL * $carry);
} }
$product_value[$j] = $carry; $product_value[$j] = $carry;
@ -498,7 +513,7 @@ abstract class PHP extends Engine
for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) { for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) {
$temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry; $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
$carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
$product_value[$k] = (int) ($temp - static::BASE_FULL * $carry); $product_value[$k] = (int)($temp - static::BASE_FULL * $carry);
} }
$product_value[$k] = $carry; $product_value[$k] = $carry;
@ -517,7 +532,8 @@ abstract class PHP extends Engine
* *
* @param \phpseclib3\Math\BigInteger\engines\PHP $y * @param \phpseclib3\Math\BigInteger\engines\PHP $y
* @return array * @return array
* @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}. * @internal This function is based off of
* {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}.
*/ */
protected function divideHelper(PHP $y) protected function divideHelper(PHP $y)
{ {
@ -683,7 +699,7 @@ abstract class PHP extends Engine
for ($i = count($dividend) - 1; $i >= 0; --$i) { for ($i = count($dividend) - 1; $i >= 0; --$i) {
$temp = static::BASE_FULL * $carry + $dividend[$i]; $temp = static::BASE_FULL * $carry + $dividend[$i];
$result[$i] = self::safe_divide($temp, $divisor); $result[$i] = self::safe_divide($temp, $divisor);
$carry = (int) ($temp - $divisor * $result[$i]); $carry = (int)($temp - $divisor * $result[$i]);
} }
return [$result, $carry]; return [$result, $carry];
@ -704,7 +720,7 @@ abstract class PHP extends Engine
private static function safe_divide($x, $y) private static function safe_divide($x, $y)
{ {
if (static::BASE === 26) { if (static::BASE === 26) {
return (int) ($x / $y); return (int)($x / $y);
} }
// static::BASE === 31 // static::BASE === 31
@ -903,7 +919,7 @@ abstract class PHP extends Engine
return; return;
} }
$num_digits = (int) ($shift / static::BASE); $num_digits = (int)($shift / static::BASE);
$shift %= static::BASE; $shift %= static::BASE;
$shift = 1 << $shift; $shift = 1 << $shift;
@ -912,7 +928,7 @@ abstract class PHP extends Engine
for ($i = 0; $i < count($this->value); ++$i) { for ($i = 0; $i < count($this->value); ++$i) {
$temp = $this->value[$i] * $shift + $carry; $temp = $this->value[$i] * $shift + $carry;
$carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
$this->value[$i] = (int) ($temp - $carry * static::BASE_FULL); $this->value[$i] = (int)($temp - $carry * static::BASE_FULL);
} }
if ($carry) { if ($carry) {
@ -937,7 +953,7 @@ abstract class PHP extends Engine
return; return;
} }
$num_digits = (int) ($shift / static::BASE); $num_digits = (int)($shift / static::BASE);
$shift %= static::BASE; $shift %= static::BASE;
$carry_shift = static::BASE - $shift; $carry_shift = static::BASE - $shift;
$carry_mask = (1 << $shift) - 1; $carry_mask = (1 << $shift) - 1;
@ -1009,13 +1025,13 @@ abstract class PHP extends Engine
$temp = $square_value[$i2] + $value[$i] * $value[$i]; $temp = $square_value[$i2] + $value[$i] * $value[$i];
$carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
$square_value[$i2] = (int) ($temp - static::BASE_FULL * $carry); $square_value[$i2] = (int)($temp - static::BASE_FULL * $carry);
// note how we start from $i+1 instead of 0 as we do in multiplication. // note how we start from $i+1 instead of 0 as we do in multiplication.
for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) { for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) {
$temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry; $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry;
$carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $carry = static::BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31);
$square_value[$k] = (int) ($temp - static::BASE_FULL * $carry); $square_value[$k] = (int)($temp - static::BASE_FULL * $carry);
} }
// the following line can yield values larger 2**15. at this point, PHP should switch // the following line can yield values larger 2**15. at this point, PHP should switch
@ -1108,9 +1124,9 @@ abstract class PHP extends Engine
* *
* ie. $s = gmp_scan1($n, 0) and $r = gmp_div_q($n, gmp_pow(gmp_init('2'), $s)); * ie. $s = gmp_scan1($n, 0) and $r = gmp_div_q($n, gmp_pow(gmp_init('2'), $s));
* *
* @see self::isPrime()
* @param PHP $r * @param PHP $r
* @return int * @return int
* @see self::isPrime()
*/ */
public static function scan1divide(PHP $r) public static function scan1divide(PHP $r)
{ {
@ -1156,7 +1172,7 @@ abstract class PHP extends Engine
*/ */
public function isOdd() public function isOdd()
{ {
return (bool) ($this->value[0] & 1); return (bool)($this->value[0] & 1);
} }
/** /**
@ -1173,7 +1189,7 @@ abstract class PHP extends Engine
return false; return false;
} }
return (bool) ($this->value[$digit] & (1 << $bit)); return (bool)($this->value[$digit] & (1 << $bit));
} }
/** /**
@ -1215,7 +1231,7 @@ abstract class PHP extends Engine
throw new \RuntimeException('Offset must be greater than 1'); throw new \RuntimeException('Offset must be greater than 1');
} }
$width = (int) ($split / static::BASE); $width = (int)($split / static::BASE);
if (!$width) { if (!$width) {
$arr = $this->bitwise_small_split($split); $arr = $this->bitwise_small_split($split);
return array_map(function ($digit) { return array_map(function ($digit) {
@ -1234,7 +1250,7 @@ abstract class PHP extends Engine
$digit = []; $digit = [];
if (!$overflow) { if (!$overflow) {
$digit = array_slice($val, $i, $width); $digit = array_slice($val, $i, $width);
$i+= $width; $i += $width;
$overflow = $split % static::BASE; $overflow = $split % static::BASE;
if ($overflow) { if ($overflow) {
$mask = (1 << $overflow) - 1; $mask = (1 << $overflow) - 1;
@ -1244,9 +1260,9 @@ abstract class PHP extends Engine
} else { } else {
$remaining = static::BASE - $overflow; $remaining = static::BASE - $overflow;
$tempsplit = $split - $remaining; $tempsplit = $split - $remaining;
$tempwidth = (int) ($tempsplit / static::BASE + 1); $tempwidth = (int)($tempsplit / static::BASE + 1);
$digit = array_slice($val, $i, $tempwidth); $digit = array_slice($val, $i, $tempwidth);
$i+= $tempwidth; $i += $tempwidth;
$tempoverflow = $tempsplit % static::BASE; $tempoverflow = $tempsplit % static::BASE;
if ($tempoverflow) { if ($tempoverflow) {
$tempmask = (1 << $tempoverflow) - 1; $tempmask = (1 << $tempoverflow) - 1;
@ -1289,9 +1305,9 @@ abstract class PHP extends Engine
$remaining = static::BASE; $remaining = static::BASE;
while ($i != $len) { while ($i != $len) {
$digit = $val[$i] & $mask; $digit = $val[$i] & $mask;
$val[$i]>>= $split; $val[$i] >>= $split;
if (!$overflow) { if (!$overflow) {
$remaining-= $split; $remaining -= $split;
$overflow = $split <= $remaining ? 0 : $split - $remaining; $overflow = $split <= $remaining ? 0 : $split - $remaining;
if (!$remaining) { if (!$remaining) {
@ -1299,10 +1315,10 @@ abstract class PHP extends Engine
$remaining = static::BASE; $remaining = static::BASE;
$overflow = 0; $overflow = 0;
} }
} else if (++$i != $len) { } elseif (++$i != $len) {
$tempmask = (1 << $overflow) - 1; $tempmask = (1 << $overflow) - 1;
$digit|= ($val[$i] & $tempmask) << $remaining; $digit |= ($val[$i] & $tempmask) << $remaining;
$val[$i]>>= $overflow; $val[$i] >>= $overflow;
$remaining = static::BASE - $overflow; $remaining = static::BASE - $overflow;
$overflow = $split <= $remaining ? 0 : $split - $remaining; $overflow = $split <= $remaining ? 0 : $split - $remaining;
} }

View File

@ -94,7 +94,7 @@ abstract class Base extends PHP
} }
if ($e->value == [2]) { if ($e->value == [2]) {
$temp = new $class; $temp = new $class();
$temp->value = $class::square($x->value); $temp->value = $class::square($x->value);
list(, $temp) = $temp->divide($n); list(, $temp) = $temp->divide($n);
return $x->normalize($temp); return $x->normalize($temp);

View File

@ -60,7 +60,7 @@ abstract class Montgomery extends Base
if ($n->value[$i]) { if ($n->value[$i]) {
$temp = decbin($n->value[$i]); $temp = decbin($n->value[$i]);
$j = strlen($temp) - strrpos($temp, '1') - 1; $j = strlen($temp) - strrpos($temp, '1') - 1;
$j+= $class::BASE * $i; $j += $class::BASE * $i;
break; break;
} }
} }

View File

@ -91,7 +91,7 @@ abstract class Barrett extends Base
$cache[self::DATA][] = [ $cache[self::DATA][] = [
'u' => $u, // m.length >> 1 (technically (m.length >> 1) + 1) 'u' => $u, // m.length >> 1 (technically (m.length >> 1) + 1)
'm1'=> $m1 // m.length 'm1' => $m1 // m.length
]; ];
} else { } else {
extract($cache[self::DATA][$key]); extract($cache[self::DATA][$key]);

View File

@ -117,19 +117,19 @@ abstract class EvalBarrett extends Base
$lsd = array_slice($n, 0, ' . $cutoff . '); $lsd = array_slice($n, 0, ' . $cutoff . ');
$msd = array_slice($n, ' . $cutoff . ');'; $msd = array_slice($n, ' . $cutoff . ');';
$code.= self::generateInlineTrim('msd'); $code .= self::generateInlineTrim('msd');
$code.= self::generateInlineMultiply('msd', $m1, 'temp', $class); $code .= self::generateInlineMultiply('msd', $m1, 'temp', $class);
$code.= self::generateInlineAdd('lsd', 'temp', 'n', $class); $code .= self::generateInlineAdd('lsd', 'temp', 'n', $class);
$code.= '$temp = array_slice($n, ' . (count($m) - 1) . ');'; $code .= '$temp = array_slice($n, ' . (count($m) - 1) . ');';
$code.= self::generateInlineMultiply('temp', $u, 'temp2', $class); $code .= self::generateInlineMultiply('temp', $u, 'temp2', $class);
$code.= self::generateInlineTrim('temp2'); $code .= self::generateInlineTrim('temp2');
$code.= $class::BASE == 26 ? $code .= $class::BASE == 26 ?
'$temp = array_slice($temp2, ' . (count($m) + 1) . ');' : '$temp = array_slice($temp2, ' . (count($m) + 1) . ');' :
'$temp = array_slice($temp2, ' . ((count($m) >> 1) + 1) . ');'; '$temp = array_slice($temp2, ' . ((count($m) >> 1) + 1) . ');';
$code.= self::generateInlineMultiply('temp', $m, 'temp2', $class); $code .= self::generateInlineMultiply('temp', $m, 'temp2', $class);
$code.= self::generateInlineTrim('temp2'); $code .= self::generateInlineTrim('temp2');
/* /*
if ($class::BASE == 26) { if ($class::BASE == 26) {
@ -138,14 +138,14 @@ abstract class EvalBarrett extends Base
} }
*/ */
$code.= self::generateInlineSubtract2('n', 'temp2', 'temp', $class); $code .= self::generateInlineSubtract2('n', 'temp2', 'temp', $class);
$subcode = self::generateInlineSubtract1('temp', $m, 'temp2', $class); $subcode = self::generateInlineSubtract1('temp', $m, 'temp2', $class);
$subcode.= '$temp = $temp2;'; $subcode .= '$temp = $temp2;';
$code.= self::generateInlineCompare($m, 'temp', $subcode); $code .= self::generateInlineCompare($m, 'temp', $subcode);
$code.= 'return $temp;'; $code .= 'return $temp;';
eval('$func = function ($n) { ' . $code . '};'); eval('$func = function ($n) { ' . $code . '};');
@ -199,50 +199,50 @@ abstract class EvalBarrett extends Base
$carry = 0;'; $carry = 0;';
for ($i = 0; $i < count($arr); $i++) { for ($i = 0; $i < count($arr); $i++) {
$regular.= ' $regular .= '
$subtemp = $' . $input . '[0] * ' . $arr[$i]; $subtemp = $' . $input . '[0] * ' . $arr[$i];
$regular.= $i ? ' + $carry;' : ';'; $regular .= $i ? ' + $carry;' : ';';
$regular.= '$carry = '; $regular .= '$carry = ';
$regular.= $class::BASE === 26 ? $regular .= $class::BASE === 26 ?
'intval($subtemp / 0x4000000);' : 'intval($subtemp / 0x4000000);' :
'$subtemp >> 31;'; '$subtemp >> 31;';
$regular.= $regular .=
'$' . $output . '[' . $i . '] = '; '$' . $output . '[' . $i . '] = ';
if ($class::BASE === 26) { if ($class::BASE === 26) {
$regular.= '(int) ('; $regular .= '(int) (';
} }
$regular.= '$subtemp - ' . $class::BASE_FULL . ' * $carry'; $regular .= '$subtemp - ' . $class::BASE_FULL . ' * $carry';
$regular.= $class::BASE === 26 ? ');' : ';'; $regular .= $class::BASE === 26 ? ');' : ';';
} }
$regular.= '$' . $output . '[' . count($arr) . '] = $carry;'; $regular .= '$' . $output . '[' . count($arr) . '] = $carry;';
$regular.= ' $regular .= '
for ($i = 1; $i < $length; ++$i) {'; for ($i = 1; $i < $length; ++$i) {';
for ($j = 0; $j < count($arr); $j++) { for ($j = 0; $j < count($arr); $j++) {
$regular.= $j ? '$k++;' : '$k = $i;'; $regular .= $j ? '$k++;' : '$k = $i;';
$regular.= ' $regular .= '
$subtemp = $' . $output . '[$k] + $' . $input . '[$i] * ' . $arr[$j]; $subtemp = $' . $output . '[$k] + $' . $input . '[$i] * ' . $arr[$j];
$regular.= $j ? ' + $carry;' : ';'; $regular .= $j ? ' + $carry;' : ';';
$regular.= '$carry = '; $regular .= '$carry = ';
$regular.= $class::BASE === 26 ? $regular .= $class::BASE === 26 ?
'intval($subtemp / 0x4000000);' : 'intval($subtemp / 0x4000000);' :
'$subtemp >> 31;'; '$subtemp >> 31;';
$regular.= $regular .=
'$' . $output . '[$k] = '; '$' . $output . '[$k] = ';
if ($class::BASE === 26) { if ($class::BASE === 26) {
$regular.= '(int) ('; $regular .= '(int) (';
} }
$regular.= '$subtemp - ' . $class::BASE_FULL . ' * $carry'; $regular .= '$subtemp - ' . $class::BASE_FULL . ' * $carry';
$regular.= $class::BASE === 26 ? ');' : ';'; $regular .= $class::BASE === 26 ? ');' : ';';
} }
$regular.= '$' . $output. '[++$k] = $carry; $carry = 0;'; $regular .= '$' . $output . '[++$k] = $carry; $carry = 0;';
$regular.= '}}'; $regular .= '}}';
//if (count($arr) < 2 * self::KARATSUBA_CUTOFF) { //if (count($arr) < 2 * self::KARATSUBA_CUTOFF) {
//} //}
@ -273,10 +273,10 @@ abstract class EvalBarrett extends Base
$carry = $sum >= ' . self::float2string($class::MAX_DIGIT2) . '; $carry = $sum >= ' . self::float2string($class::MAX_DIGIT2) . ';
$sum = $carry ? $sum - ' . self::float2string($class::MAX_DIGIT2) . ' : $sum;'; $sum = $carry ? $sum - ' . self::float2string($class::MAX_DIGIT2) . ' : $sum;';
$code.= $class::BASE === 26 ? $code .= $class::BASE === 26 ?
'$upper = intval($sum / 0x4000000); $' . $result . '[$i] = (int) ($sum - ' . $class::BASE_FULL . ' * $upper);' : '$upper = intval($sum / 0x4000000); $' . $result . '[$i] = (int) ($sum - ' . $class::BASE_FULL . ' * $upper);' :
'$upper = $sum >> 31; $' . $result . '[$i] = $sum - ' . $class::BASE_FULL . ' * $upper;'; '$upper = $sum >> 31; $' . $result . '[$i] = $sum - ' . $class::BASE_FULL . ' * $upper;';
$code.= ' $code .= '
$' . $result . '[$j] = $upper; $' . $result . '[$j] = $upper;
} }
if ($j == $length) { if ($j == $length) {
@ -290,7 +290,7 @@ abstract class EvalBarrett extends Base
} }
++$' . $result . '[$i]; ++$' . $result . '[$i];
}'; }';
$code.= self::generateInlineTrim($result); $code .= self::generateInlineTrim($result);
return $code; return $code;
} }
@ -309,7 +309,7 @@ abstract class EvalBarrett extends Base
private static function generateInlineSubtract2($known, $unknown, $result, $class) private static function generateInlineSubtract2($known, $unknown, $result, $class)
{ {
$code = ' $code = '
$' . $result .' = $' . $known . '; $' . $result . ' = $' . $known . ';
$carry = 0; $carry = 0;
$size = count($' . $unknown . '); $size = count($' . $unknown . ');
for ($i = 0, $j = 1; $j < $size; $i+= 2, $j+= 2) { for ($i = 0, $j = 1; $j < $size; $i+= 2, $j+= 2) {
@ -321,18 +321,18 @@ abstract class EvalBarrett extends Base
$sum+= ' . self::float2string($class::MAX_DIGIT2) . '; $sum+= ' . self::float2string($class::MAX_DIGIT2) . ';
} }
$subtemp = '; $subtemp = ';
$code.= $class::BASE === 26 ? $code .= $class::BASE === 26 ?
'intval($sum / 0x4000000);' : 'intval($sum / 0x4000000);' :
'$sum >> 31;'; '$sum >> 31;';
$code.= '$' . $result . '[$i] = '; $code .= '$' . $result . '[$i] = ';
if ($class::BASE === 26) { if ($class::BASE === 26) {
$code.= '(int) ('; $code .= '(int) (';
} }
$code.= '$sum - ' . $class::BASE_FULL . ' * $subtemp'; $code .= '$sum - ' . $class::BASE_FULL . ' * $subtemp';
if ($class::BASE === 26) { if ($class::BASE === 26) {
$code.= ')'; $code .= ')';
} }
$code.= '; $code .= ';
$' . $result . '[$j] = $subtemp; $' . $result . '[$j] = $subtemp;
} }
if ($j == $size) { if ($j == $size) {
@ -349,7 +349,7 @@ abstract class EvalBarrett extends Base
--$' . $result . '[$i]; --$' . $result . '[$i];
}'; }';
$code.= self::generateInlineTrim($result); $code .= self::generateInlineTrim($result);
return $code; return $code;
} }
@ -368,52 +368,52 @@ abstract class EvalBarrett extends Base
private static function generateInlineSubtract1($unknown, array $known, $result, $class) private static function generateInlineSubtract1($unknown, array $known, $result, $class)
{ {
$code = '$' . $result . ' = $' . $unknown . ';'; $code = '$' . $result . ' = $' . $unknown . ';';
for ($i = 0, $j = 1; $j < count($known); $i+=2, $j+=2) { for ($i = 0, $j = 1; $j < count($known); $i += 2, $j += 2) {
$code.= '$sum = $' . $unknown . '[' . $j . '] * ' . $class::BASE_FULL . ' + $' . $unknown . '[' . $i . '] - '; $code .= '$sum = $' . $unknown . '[' . $j . '] * ' . $class::BASE_FULL . ' + $' . $unknown . '[' . $i . '] - ';
$code.= self::float2string($known[$j] * $class::BASE_FULL + $known[$i]); $code .= self::float2string($known[$j] * $class::BASE_FULL + $known[$i]);
if ($i != 0) { if ($i != 0) {
$code.= ' - $carry'; $code .= ' - $carry';
} }
$code.= '; $code .= ';
if ($carry = $sum < 0) { if ($carry = $sum < 0) {
$sum+= ' . self::float2string($class::MAX_DIGIT2) . '; $sum+= ' . self::float2string($class::MAX_DIGIT2) . ';
} }
$subtemp = '; $subtemp = ';
$code.= $class::BASE === 26 ? $code .= $class::BASE === 26 ?
'intval($sum / 0x4000000);' : 'intval($sum / 0x4000000);' :
'$sum >> 31;'; '$sum >> 31;';
$code.= ' $code .= '
$' . $result . '[' . $i . '] = '; $' . $result . '[' . $i . '] = ';
if ($class::BASE === 26) { if ($class::BASE === 26) {
$code.= ' (int) ('; $code .= ' (int) (';
} }
$code.= '$sum - ' . $class::BASE_FULL . ' * $subtemp'; $code .= '$sum - ' . $class::BASE_FULL . ' * $subtemp';
if ($class::BASE === 26) { if ($class::BASE === 26) {
$code.= ')'; $code .= ')';
} }
$code.= '; $code .= ';
$' . $result . '[' . $j . '] = $subtemp;'; $' . $result . '[' . $j . '] = $subtemp;';
} }
$code.= '$i = ' . $i . ';'; $code .= '$i = ' . $i . ';';
if ($j == count($known)) { if ($j == count($known)) {
$code.= ' $code .= '
$sum = $' . $unknown . '[' . $i . '] - ' . $known[$i] . ' - $carry; $sum = $' . $unknown . '[' . $i . '] - ' . $known[$i] . ' - $carry;
$carry = $sum < 0; $carry = $sum < 0;
$' . $result . '[' . $i . '] = $carry ? $sum + ' . $class::BASE_FULL . ' : $sum; $' . $result . '[' . $i . '] = $carry ? $sum + ' . $class::BASE_FULL . ' : $sum;
++$i;'; ++$i;';
} }
$code.= ' $code .= '
if ($carry) { if ($carry) {
for (; !$' . $result . '[$i]; ++$i) { for (; !$' . $result . '[$i]; ++$i) {
$' . $result . '[$i] = ' . $class::MAX_DIGIT . '; $' . $result . '[$i] = ' . $class::MAX_DIGIT . ';
} }
--$' . $result . '[$i]; --$' . $result . '[$i];
}'; }';
$code.= self::generateInlineTrim($result); $code .= self::generateInlineTrim($result);
return $code; return $code;
} }
@ -438,13 +438,13 @@ abstract class EvalBarrett extends Base
goto end_' . $uniqid . '; goto end_' . $uniqid . ';
case $clength > ' . count($known) . ':'; case $clength > ' . count($known) . ':';
for ($i = count($known) - 1; $i >= 0; $i--) { for ($i = count($known) - 1; $i >= 0; $i--) {
$code.= ' $code .= '
case $' . $unknown . '[' . $i . '] > ' . $known[$i] . ': case $' . $unknown . '[' . $i . '] > ' . $known[$i] . ':
goto subcode_' . $uniqid . '; goto subcode_' . $uniqid . ';
case $' . $unknown . '[' . $i . '] < ' . $known[$i] . ': case $' . $unknown . '[' . $i . '] < ' . $known[$i] . ':
goto end_' . $uniqid . ';'; goto end_' . $uniqid . ';';
} }
$code.= ' $code .= '
default: default:
// do subcode // do subcode
} }

View File

@ -15,7 +15,6 @@
namespace phpseclib3\Math\BigInteger\Engines\PHP\Reductions; namespace phpseclib3\Math\BigInteger\Engines\PHP\Reductions;
/** /**
* PHP Montgomery Modular Exponentiation Engine with interleaved multiplication * PHP Montgomery Modular Exponentiation Engine with interleaved multiplication
* *

View File

@ -15,7 +15,6 @@
namespace phpseclib3\Math\BigInteger\Engines; namespace phpseclib3\Math\BigInteger\Engines;
/** /**
* Pure-PHP 32-bit Engine. * Pure-PHP 32-bit Engine.
* *
@ -110,7 +109,7 @@ class PHP32 extends PHP
} }
while (true) { while (true) {
$i-= 4; $i -= 4;
if ($i < 0) { if ($i < 0) {
if ($i == -4) { if ($i == -4) {
break; break;
@ -125,10 +124,10 @@ class PHP32 extends PHP
list(, $digit) = unpack('N', substr($val, $i, 4)); list(, $digit) = unpack('N', substr($val, $i, 4));
$step = count($vals) & 3; $step = count($vals) & 3;
if ($step) { if ($step) {
$digit>>= 2 * $step; $digit >>= 2 * $step;
} }
if ($step != 3) { if ($step != 3) {
$digit&= static::MAX_DIGIT; $digit &= static::MAX_DIGIT;
$i++; $i++;
} }
$vals[] = $digit; $vals[] = $digit;

View File

@ -15,7 +15,6 @@
namespace phpseclib3\Math\BigInteger\Engines; namespace phpseclib3\Math\BigInteger\Engines;
/** /**
* Pure-PHP 64-bit Engine. * Pure-PHP 64-bit Engine.
* *
@ -110,7 +109,7 @@ class PHP64 extends PHP
} }
while (true) { while (true) {
$i-= 4; $i -= 4;
if ($i < 0) { if ($i < 0) {
if ($i == -4) { if ($i == -4) {
break; break;
@ -125,15 +124,15 @@ class PHP64 extends PHP
list(, $digit) = unpack('N', substr($val, $i, 4)); list(, $digit) = unpack('N', substr($val, $i, 4));
$step = count($vals) & 7; $step = count($vals) & 7;
if (!$step) { if (!$step) {
$digit&= static::MAX_DIGIT; $digit &= static::MAX_DIGIT;
$i++; $i++;
} else { } else {
$shift = 8 - $step; $shift = 8 - $step;
$digit>>= $shift; $digit >>= $shift;
$shift = 32 - $shift; $shift = 32 - $shift;
$digit&= (1 << $shift) - 1; $digit &= (1 << $shift) - 1;
$temp = $i > 0 ? ord($val[$i - 1]) : 0; $temp = $i > 0 ? ord($val[$i - 1]) : 0;
$digit|= ($temp << $shift) & 0x7F000000; $digit |= ($temp << $shift) & 0x7F000000;
} }
$vals[] = $digit; $vals[] = $digit;
} }

View File

@ -74,7 +74,7 @@ class BinaryField extends FiniteField
// implements algorithm 2.40 (in section 2.3.5) in "Guide to Elliptic Curve Cryptography" // implements algorithm 2.40 (in section 2.3.5) in "Guide to Elliptic Curve Cryptography"
// with W = 8 // with W = 8
$reduce = function($c) use ($u, $mStart, $m, $t, $finalMask, $pad, $h) { $reduce = function ($c) use ($u, $mStart, $m, $t, $finalMask, $pad, $h) {
$c = str_pad($c, $pad, "\0", STR_PAD_LEFT); $c = str_pad($c, $pad, "\0", STR_PAD_LEFT);
for ($i = $mStart; $i >= $m;) { for ($i = $mStart; $i >= $m;) {
$g = $h >> 3; $g = $h >> 3;

View File

@ -216,7 +216,7 @@ class Integer extends Base
for ($i = 0; $i < strlen($y); $i++) { for ($i = 0; $i < strlen($y); $i++) {
if ($y[$i] == '1') { if ($y[$i] == '1') {
$temp = $precomputed[$i & 7] . str_repeat("\0", $i >> 3); $temp = $precomputed[$i & 7] . str_repeat("\0", $i >> 3);
$result^= str_pad($temp, $size, "\0", STR_PAD_LEFT); $result ^= str_pad($temp, $size, "\0", STR_PAD_LEFT);
} }
} }
@ -304,10 +304,10 @@ class Integer extends Base
$z2 = ($x0 * $y2) ^ ($x1 * $y1) ^ ($x2 * $y0) ^ ($x3 * $y3); $z2 = ($x0 * $y2) ^ ($x1 * $y1) ^ ($x2 * $y0) ^ ($x3 * $y3);
$z3 = ($x0 * $y3) ^ ($x1 * $y2) ^ ($x2 * $y1) ^ ($x3 * $y0); $z3 = ($x0 * $y3) ^ ($x1 * $y2) ^ ($x2 * $y1) ^ ($x3 * $y0);
$z0&= 0x1111111111111111; $z0 &= 0x1111111111111111;
$z1&= 0x2222222222222222; $z1 &= 0x2222222222222222;
$z2&= 0x4444444444444444; $z2 &= 0x4444444444444444;
$z3&= -8608480567731124088; // 0x8888888888888888 gets interpreted as a float $z3 &= -8608480567731124088; // 0x8888888888888888 gets interpreted as a float
$z = $z0 | $z1 | $z2 | $z3; $z = $z0 | $z1 | $z2 | $z3;

View File

@ -433,7 +433,7 @@ class SFTP extends SSH2
if ($response === false) { if ($response === false) {
return false; return false;
} }
} else if ($response === true && $this->isTimeout()) { } elseif ($response === true && $this->isTimeout()) {
return false; return false;
} }
@ -747,7 +747,7 @@ class SFTP extends SSH2
$dir = './'; $dir = './';
// suffix a slash if needed // suffix a slash if needed
} elseif ($dir[strlen($dir) - 1] != '/') { } elseif ($dir[strlen($dir) - 1] != '/') {
$dir.= '/'; $dir .= '/';
} }
$dir = $this->realpath($dir); $dir = $this->realpath($dir);
@ -1040,8 +1040,8 @@ class SFTP extends SSH2
} }
break; break;
case 'mode': case 'mode':
$a[$sort]&= 07777; $a[$sort] &= 07777;
$b[$sort]&= 07777; $b[$sort] &= 07777;
default: default:
if ($a[$sort] === $b[$sort]) { if ($a[$sort] === $b[$sort]) {
break; break;
@ -1079,7 +1079,7 @@ class SFTP extends SSH2
return; return;
} }
$len = count($args) & 0x7FFFFFFE; $len = count($args) & 0x7FFFFFFE;
for ($i = 0; $i < $len; $i+=2) { for ($i = 0; $i < $len; $i += 2) {
$this->sortOptions[$args[$i]] = $args[$i + 1]; $this->sortOptions[$args[$i]] = $args[$i + 1];
} }
if (!count($this->sortOptions)) { if (!count($this->sortOptions)) {
@ -1222,7 +1222,7 @@ class SFTP extends SSH2
} }
if (isset($stat['type'])) { if (isset($stat['type'])) {
if ($stat['type'] == FileType::DIRECTORY) { if ($stat['type'] == FileType::DIRECTORY) {
$filename.= '/.'; $filename .= '/.';
} }
$this->update_stat_cache($filename, (object) ['stat' => $stat]); $this->update_stat_cache($filename, (object) ['stat' => $stat]);
return $stat; return $stat;
@ -1235,7 +1235,7 @@ class SFTP extends SSH2
$this->pwd = $pwd; $this->pwd = $pwd;
if ($stat['type'] == FileType::DIRECTORY) { if ($stat['type'] == FileType::DIRECTORY) {
$filename.= '/.'; $filename .= '/.';
} }
$this->update_stat_cache($filename, (object) ['stat' => $stat]); $this->update_stat_cache($filename, (object) ['stat' => $stat]);
@ -1279,7 +1279,7 @@ class SFTP extends SSH2
} }
if (isset($lstat['type'])) { if (isset($lstat['type'])) {
if ($lstat['type'] == FileType::DIRECTORY) { if ($lstat['type'] == FileType::DIRECTORY) {
$filename.= '/.'; $filename .= '/.';
} }
$this->update_stat_cache($filename, (object) ['lstat' => $lstat]); $this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
return $lstat; return $lstat;
@ -1300,7 +1300,7 @@ class SFTP extends SSH2
$this->pwd = $pwd; $this->pwd = $pwd;
if ($lstat['type'] == FileType::DIRECTORY) { if ($lstat['type'] == FileType::DIRECTORY) {
$filename.= '/.'; $filename .= '/.';
} }
$this->update_stat_cache($filename, (object) ['lstat' => $lstat]); $this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
@ -1388,10 +1388,10 @@ class SFTP extends SSH2
Strings::packSSH2('NQ2', Attribute::ACCESSTIME | Attribute::MODIFYTIME, $atime, $time); Strings::packSSH2('NQ2', Attribute::ACCESSTIME | Attribute::MODIFYTIME, $atime, $time);
$packet = Strings::packSSH2('s', $filename); $packet = Strings::packSSH2('s', $filename);
$packet.= $this->version >= 5 ? $packet .= $this->version >= 5 ?
pack('N2', 0, OpenFlag5::OPEN_EXISTING) : pack('N2', 0, OpenFlag5::OPEN_EXISTING) :
pack('N', OpenFlag::WRITE | OpenFlag::CREATE | OpenFlag::EXCL); pack('N', OpenFlag::WRITE | OpenFlag::CREATE | OpenFlag::EXCL);
$packet.= $attr; $packet .= $attr;
$this->send_sftp_packet(SftpPacketType::OPEN, $packet); $this->send_sftp_packet(SftpPacketType::OPEN, $packet);
@ -1564,7 +1564,7 @@ class SFTP extends SSH2
} }
$packet = Strings::packSSH2('s', $filename); $packet = Strings::packSSH2('s', $filename);
$packet.= $this->version >= 4 ? $packet .= $this->version >= 4 ?
pack('a*Ca*', substr($attr, 0, 4), FileType::UNKNOWN, substr($attr, 4)) : pack('a*Ca*', substr($attr, 0, 4), FileType::UNKNOWN, substr($attr, 4)) :
$attr; $attr;
$this->send_sftp_packet(SftpPacketType::SETSTAT, $packet); $this->send_sftp_packet(SftpPacketType::SETSTAT, $packet);
@ -1633,7 +1633,7 @@ class SFTP extends SSH2
} }
} else { } else {
$packet = Strings::packSSH2('s', $temp); $packet = Strings::packSSH2('s', $temp);
$packet.= $this->version >= 4 ? $packet .= $this->version >= 4 ?
pack('Ca*', FileType::UNKNOWN, $attr) : pack('Ca*', FileType::UNKNOWN, $attr) :
$attr; $attr;
$this->send_sftp_packet(SftpPacketType::SETSTAT, $packet); $this->send_sftp_packet(SftpPacketType::SETSTAT, $packet);
@ -1650,7 +1650,7 @@ class SFTP extends SSH2
} }
$packet = Strings::packSSH2('s', $path); $packet = Strings::packSSH2('s', $path);
$packet.= $this->version >= 4 ? $packet .= $this->version >= 4 ?
pack('Ca*', FileType::UNKNOWN, $attr) : pack('Ca*', FileType::UNKNOWN, $attr) :
$attr; $attr;
$this->send_sftp_packet(SftpPacketType::SETSTAT, $packet); $this->send_sftp_packet(SftpPacketType::SETSTAT, $packet);
@ -1967,14 +1967,14 @@ class SFTP extends SSH2
if ($this->version >= 5) { if ($this->version >= 5) {
$flags = OpenFlag5::CREATE_TRUNCATE; $flags = OpenFlag5::CREATE_TRUNCATE;
} else { } else {
$flags|= OpenFlag::TRUNCATE; $flags |= OpenFlag::TRUNCATE;
} }
} }
$this->remove_from_stat_cache($remote_file); $this->remove_from_stat_cache($remote_file);
$packet = Strings::packSSH2('s', $remote_file); $packet = Strings::packSSH2('s', $remote_file);
$packet.= $this->version >= 5 ? $packet .= $this->version >= 5 ?
pack('N3', 0, $flags, 0) : pack('N3', 0, $flags, 0) :
pack('N2', $flags, 0); pack('N2', $flags, 0);
$this->send_sftp_packet(SftpPacketType::OPEN, $packet); $this->send_sftp_packet(SftpPacketType::OPEN, $packet);
@ -2029,7 +2029,7 @@ class SFTP extends SSH2
if ($local_start >= 0) { if ($local_start >= 0) {
fseek($fp, $local_start); fseek($fp, $local_start);
$size-= $local_start; $size -= $local_start;
} }
} elseif ($dataCallback) { } elseif ($dataCallback) {
$size = 0; $size = 0;
@ -2042,7 +2042,7 @@ class SFTP extends SSH2
$sftp_packet_size = $this->max_sftp_packet; $sftp_packet_size = $this->max_sftp_packet;
// make the SFTP packet be exactly the SFTP packet size by including the bytes in the PacketType::WRITE packets "header" // make the SFTP packet be exactly the SFTP packet size by including the bytes in the PacketType::WRITE packets "header"
$sftp_packet_size-= strlen($handle) + 25; $sftp_packet_size -= strlen($handle) + 25;
$i = $j = 0; $i = $j = 0;
while ($dataCallback || ($size === 0 || $sent < $size)) { while ($dataCallback || ($size === 0 || $sent < $size)) {
if ($dataCallback) { if ($dataCallback) {
@ -2067,7 +2067,7 @@ class SFTP extends SSH2
} }
throw $e; throw $e;
} }
$sent+= strlen($temp); $sent += strlen($temp);
if (is_callable($progressCallback)) { if (is_callable($progressCallback)) {
$progressCallback($sent); $progressCallback($sent);
} }
@ -2201,7 +2201,7 @@ class SFTP extends SSH2
} }
$packet = Strings::packSSH2('s', $remote_file); $packet = Strings::packSSH2('s', $remote_file);
$packet.= $this->version >= 5 ? $packet .= $this->version >= 5 ?
pack('N3', 0, OpenFlag5::OPEN_EXISTING, 0) : pack('N3', 0, OpenFlag5::OPEN_EXISTING, 0) :
pack('N2', OpenFlag::READ, 0); pack('N2', OpenFlag::READ, 0);
$this->send_sftp_packet(SftpPacketType::OPEN, $packet); $this->send_sftp_packet(SftpPacketType::OPEN, $packet);
@ -2257,7 +2257,7 @@ class SFTP extends SSH2
throw $e; throw $e;
} }
$packet = null; $packet = null;
$read+= $packet_size; $read += $packet_size;
$i++; $i++;
} }
@ -2281,9 +2281,9 @@ class SFTP extends SSH2
switch ($this->packet_type) { switch ($this->packet_type) {
case SftpPacketType::DATA: case SftpPacketType::DATA:
$temp = substr($response, 4); $temp = substr($response, 4);
$offset+= strlen($temp); $offset += strlen($temp);
if ($local_file === false) { if ($local_file === false) {
$content.= $temp; $content .= $temp;
} elseif (is_callable($local_file)) { } elseif (is_callable($local_file)) {
$local_file($temp); $local_file($temp);
} else { } else {
@ -2817,7 +2817,7 @@ class SFTP extends SSH2
SSH_FXP_RENAME_NATIVE 0x00000004 SSH_FXP_RENAME_NATIVE 0x00000004
(none of these are currently supported) */ (none of these are currently supported) */
$packet.= "\0\0\0\0"; $packet .= "\0\0\0\0";
} }
$this->send_sftp_packet(SftpPacketType::RENAME, $packet); $this->send_sftp_packet(SftpPacketType::RENAME, $packet);
@ -2929,21 +2929,21 @@ class SFTP extends SSH2
list($attr['mode']) = Strings::unpackSSH2('N', $response); list($attr['mode']) = Strings::unpackSSH2('N', $response);
$fileType = $this->parseMode($attr['mode']); $fileType = $this->parseMode($attr['mode']);
if ($this->version < 4 && $fileType !== false) { if ($this->version < 4 && $fileType !== false) {
$attr+= ['type' => $fileType]; $attr += ['type' => $fileType];
} }
break; break;
case Attribute::ACCESSTIME: // 0x00000008 case Attribute::ACCESSTIME: // 0x00000008
if ($this->version >= 4) { if ($this->version >= 4) {
$attr+= $this->parseTime('atime', $flags, $response); $attr += $this->parseTime('atime', $flags, $response);
break; break;
} }
list($attr['atime'], $attr['mtime']) = Strings::unpackSSH2('NN', $response); list($attr['atime'], $attr['mtime']) = Strings::unpackSSH2('NN', $response);
break; break;
case Attribute::CREATETIME: // 0x00000010 (SFTPv4+) case Attribute::CREATETIME: // 0x00000010 (SFTPv4+)
$attr+= $this->parseTime('createtime', $flags, $response); $attr += $this->parseTime('createtime', $flags, $response);
break; break;
case Attribute::MODIFYTIME: // 0x00000020 case Attribute::MODIFYTIME: // 0x00000020
$attr+= $this->parseTime('mtime', $flags, $response); $attr += $this->parseTime('mtime', $flags, $response);
break; break;
case Attribute::ACL: // 0x00000040 case Attribute::ACL: // 0x00000040
// access control list // access control list
@ -2998,7 +2998,7 @@ class SFTP extends SSH2
case Attribute::CTIME: // 0x00008000 case Attribute::CTIME: // 0x00008000
// 'ctime' contains the last time the file attributes were changed. The // 'ctime' contains the last time the file attributes were changed. The
// exact meaning of this field depends on the server. // exact meaning of this field depends on the server.
$attr+= $this->parseTime('ctime', $flags, $response); $attr += $this->parseTime('ctime', $flags, $response);
break; break;
case Attribute::EXTENDED: // 0x80000000 case Attribute::EXTENDED: // 0x80000000
list($count) = Strings::unpackSSH2('N', $response); list($count) = Strings::unpackSSH2('N', $response);
@ -3198,7 +3198,7 @@ class SFTP extends SSH2
$this->packet_buffer = ''; $this->packet_buffer = '';
return false; return false;
} }
$this->packet_buffer.= $temp; $this->packet_buffer .= $temp;
} }
if (strlen($this->packet_buffer) < 4) { if (strlen($this->packet_buffer) < 4) {
throw new \RuntimeException('Packet is too small'); throw new \RuntimeException('Packet is too small');
@ -3207,7 +3207,7 @@ class SFTP extends SSH2
/** @var integer $length */ /** @var integer $length */
$tempLength = $length; $tempLength = $length;
$tempLength-= strlen($this->packet_buffer); $tempLength -= strlen($this->packet_buffer);
// 256 * 1024 is what SFTP_MAX_MSG_LENGTH is set to in OpenSSH's sftp-common.h // 256 * 1024 is what SFTP_MAX_MSG_LENGTH is set to in OpenSSH's sftp-common.h
if (!$this->allow_arbitrary_length_packets && !$this->use_request_id && $tempLength > 256 * 1024) { if (!$this->allow_arbitrary_length_packets && !$this->use_request_id && $tempLength > 256 * 1024) {
@ -3222,8 +3222,8 @@ class SFTP extends SSH2
$this->packet_buffer = ''; $this->packet_buffer = '';
return false; return false;
} }
$this->packet_buffer.= $temp; $this->packet_buffer .= $temp;
$tempLength-= strlen($temp); $tempLength -= strlen($temp);
} }
$stop = microtime(true); $stop = microtime(true);
@ -3232,9 +3232,9 @@ class SFTP extends SSH2
if ($this->use_request_id) { if ($this->use_request_id) {
extract(unpack('Npacket_id', Strings::shift($this->packet_buffer, 4))); // remove the request id extract(unpack('Npacket_id', Strings::shift($this->packet_buffer, 4))); // remove the request id
$length-= 5; // account for the request id and the packet type $length -= 5; // account for the request id and the packet type
} else { } else {
$length-= 1; // account for the packet type $length -= 1; // account for the packet type
} }
$packet = Strings::shift($this->packet_buffer, $length); $packet = Strings::shift($this->packet_buffer, $length);

View File

@ -38,7 +38,7 @@ class Stream
* *
* @var array * @var array
*/ */
static $instances; public static $instances;
/** /**
* SFTP instance * SFTP instance
@ -158,14 +158,14 @@ class Stream
$orig = $path; $orig = $path;
extract(parse_url($path) + ['port' => 22]); extract(parse_url($path) + ['port' => 22]);
if (isset($query)) { if (isset($query)) {
$path.= '?' . $query; $path .= '?' . $query;
} elseif (preg_match('/(\?|\?#)$/', $orig)) { } elseif (preg_match('/(\?|\?#)$/', $orig)) {
$path.= '?'; $path .= '?';
} }
if (isset($fragment)) { if (isset($fragment)) {
$path.= '#' . $fragment; $path .= '#' . $fragment;
} elseif ($orig[strlen($orig) - 1] == '#') { } elseif ($orig[strlen($orig) - 1] == '#') {
$path.= '#'; $path .= '#';
} }
if (!isset($host)) { if (!isset($host)) {
@ -330,7 +330,7 @@ class Stream
$this->eof = true; $this->eof = true;
return false; return false;
} }
$this->pos+= strlen($result); $this->pos += strlen($result);
return $result; return $result;
} }
@ -362,7 +362,7 @@ class Stream
if ($result === false) { if ($result === false) {
return false; return false;
} }
$this->pos+= strlen($data); $this->pos += strlen($data);
if ($this->pos > $this->size) { if ($this->pos > $this->size) {
$this->size = $this->pos; $this->size = $this->pos;
} }
@ -416,10 +416,10 @@ class Stream
} }
break; break;
case SEEK_CUR: case SEEK_CUR:
$offset+= $this->pos; $offset += $this->pos;
break; break;
case SEEK_END: case SEEK_END:
$offset+= $this->size; $offset += $this->size;
} }
$this->pos = $offset; $this->pos = $offset;

View File

@ -1288,7 +1288,7 @@ class SSH2
$elapsed = microtime(true) - $start; $elapsed = microtime(true) - $start;
if ($this->curTimeout) { if ($this->curTimeout) {
$this->curTimeout-= $elapsed; $this->curTimeout -= $elapsed;
if ($this->curTimeout < 0) { if ($this->curTimeout < 0) {
throw new \RuntimeException('Connection timed out whilst attempting to open socket connection'); throw new \RuntimeException('Connection timed out whilst attempting to open socket connection');
} }
@ -1325,7 +1325,7 @@ class SSH2
throw new \RuntimeException('Connection timed out whilst receiving server identification string'); throw new \RuntimeException('Connection timed out whilst receiving server identification string');
} }
$elapsed = microtime(true) - $start; $elapsed = microtime(true) - $start;
$this->curTimeout-= $elapsed; $this->curTimeout -= $elapsed;
} }
$temp = stream_get_line($this->fsock, 255, "\n"); $temp = stream_get_line($this->fsock, 255, "\n");
@ -1336,7 +1336,7 @@ class SSH2
continue; continue;
} }
$line.= "$temp\n"; $line .= "$temp\n";
// quoting RFC4253, "Implementers who wish to maintain // quoting RFC4253, "Implementers who wish to maintain
// compatibility with older, undocumented versions of this protocol may // compatibility with older, undocumented versions of this protocol may
@ -1351,7 +1351,7 @@ class SSH2
break; break;
} }
$data.= $line; $data .= $line;
} }
if (feof($this->fsock)) { if (feof($this->fsock)) {
@ -1395,7 +1395,7 @@ class SSH2
$this->key_exchange(); $this->key_exchange();
} }
$this->bitmap|= self::MASK_CONNECTED; $this->bitmap |= self::MASK_CONNECTED;
return true; return true;
} }
@ -1497,7 +1497,7 @@ class SSH2
$client_cookie = Random::string(16); $client_cookie = Random::string(16);
$kexinit_payload_client = pack('Ca*', MessageType::KEXINIT, $client_cookie); $kexinit_payload_client = pack('Ca*', MessageType::KEXINIT, $client_cookie);
$kexinit_payload_client.= Strings::packSSH2( $kexinit_payload_client .= Strings::packSSH2(
'L10bN', 'L10bN',
$kex_algorithms, $kex_algorithms,
$server_host_key_algorithms, $server_host_key_algorithms,
@ -1746,15 +1746,17 @@ class SSH2
$keyBytes = "\0$keyBytes"; $keyBytes = "\0$keyBytes";
} }
$this->exchange_hash = Strings::packSSH2('s5', $this->exchange_hash = Strings::packSSH2(
's5',
$this->identifier, $this->identifier,
$this->server_identifier, $this->server_identifier,
$kexinit_payload_client, $kexinit_payload_client,
$kexinit_payload_server, $kexinit_payload_server,
$this->server_public_host_key $this->server_public_host_key
); );
$this->exchange_hash.= $exchange_hash_rfc4419; $this->exchange_hash .= $exchange_hash_rfc4419;
$this->exchange_hash.= Strings::packSSH2('s3', $this->exchange_hash .= Strings::packSSH2(
's3',
$ourPublicBytes, $ourPublicBytes,
$theirPublicBytes, $theirPublicBytes,
$keyBytes $keyBytes
@ -1816,7 +1818,7 @@ class SSH2
if ($this->encrypt->usesIV()) { if ($this->encrypt->usesIV()) {
$iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'A' . $this->session_id); $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'A' . $this->session_id);
while ($this->encrypt_block_size > strlen($iv)) { while ($this->encrypt_block_size > strlen($iv)) {
$iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv); $iv .= $kexHash->hash($keyBytes . $this->exchange_hash . $iv);
} }
$this->encrypt->setIV(substr($iv, 0, $this->encrypt_block_size)); $this->encrypt->setIV(substr($iv, 0, $this->encrypt_block_size));
} }
@ -1835,7 +1837,7 @@ class SSH2
$key = $kexHash->hash($keyBytes . $this->exchange_hash . 'C' . $this->session_id); $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'C' . $this->session_id);
while ($encryptKeyLength > strlen($key)) { while ($encryptKeyLength > strlen($key)) {
$key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); $key .= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
} }
switch ($encrypt) { switch ($encrypt) {
case 'chacha20-poly1305@openssh.com': case 'chacha20-poly1305@openssh.com':
@ -1860,7 +1862,7 @@ class SSH2
if ($this->decrypt->usesIV()) { if ($this->decrypt->usesIV()) {
$iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'B' . $this->session_id); $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'B' . $this->session_id);
while ($this->decrypt_block_size > strlen($iv)) { while ($this->decrypt_block_size > strlen($iv)) {
$iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv); $iv .= $kexHash->hash($keyBytes . $this->exchange_hash . $iv);
} }
$this->decrypt->setIV(substr($iv, 0, $this->decrypt_block_size)); $this->decrypt->setIV(substr($iv, 0, $this->decrypt_block_size));
} }
@ -1880,7 +1882,7 @@ class SSH2
$key = $kexHash->hash($keyBytes . $this->exchange_hash . 'D' . $this->session_id); $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'D' . $this->session_id);
while ($decryptKeyLength > strlen($key)) { while ($decryptKeyLength > strlen($key)) {
$key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); $key .= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
} }
switch ($decrypt) { switch ($decrypt) {
case 'chacha20-poly1305@openssh.com': case 'chacha20-poly1305@openssh.com':
@ -1909,7 +1911,7 @@ class SSH2
if (!$this->encrypt->usesNonce()) { if (!$this->encrypt->usesNonce()) {
list($this->hmac_create, $createKeyLength) = self::mac_algorithm_to_hash_instance($mac_algorithm_out); list($this->hmac_create, $createKeyLength) = self::mac_algorithm_to_hash_instance($mac_algorithm_out);
} else { } else {
$this->hmac_create = new \stdClass; $this->hmac_create = new \stdClass();
$this->hmac_create_name = $mac_algorithm_out; $this->hmac_create_name = $mac_algorithm_out;
//$mac_algorithm_out = 'none'; //$mac_algorithm_out = 'none';
$createKeyLength = 0; $createKeyLength = 0;
@ -1918,7 +1920,7 @@ class SSH2
if ($this->hmac_create instanceof Hash) { if ($this->hmac_create instanceof Hash) {
$key = $kexHash->hash($keyBytes . $this->exchange_hash . 'E' . $this->session_id); $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'E' . $this->session_id);
while ($createKeyLength > strlen($key)) { while ($createKeyLength > strlen($key)) {
$key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); $key .= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
} }
$this->hmac_create->setKey(substr($key, 0, $createKeyLength)); $this->hmac_create->setKey(substr($key, 0, $createKeyLength));
$this->hmac_create_name = $mac_algorithm_out; $this->hmac_create_name = $mac_algorithm_out;
@ -1929,7 +1931,7 @@ class SSH2
list($this->hmac_check, $checkKeyLength) = self::mac_algorithm_to_hash_instance($mac_algorithm_in); list($this->hmac_check, $checkKeyLength) = self::mac_algorithm_to_hash_instance($mac_algorithm_in);
$this->hmac_size = $this->hmac_check->getLengthInBytes(); $this->hmac_size = $this->hmac_check->getLengthInBytes();
} else { } else {
$this->hmac_check = new \stdClass; $this->hmac_check = new \stdClass();
$this->hmac_check_name = $mac_algorithm_in; $this->hmac_check_name = $mac_algorithm_in;
//$mac_algorithm_in = 'none'; //$mac_algorithm_in = 'none';
$checkKeyLength = 0; $checkKeyLength = 0;
@ -1939,7 +1941,7 @@ class SSH2
if ($this->hmac_check instanceof Hash) { if ($this->hmac_check instanceof Hash) {
$key = $kexHash->hash($keyBytes . $this->exchange_hash . 'F' . $this->session_id); $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'F' . $this->session_id);
while ($checkKeyLength > strlen($key)) { while ($checkKeyLength > strlen($key)) {
$key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); $key .= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
} }
$this->hmac_check->setKey(substr($key, 0, $checkKeyLength)); $this->hmac_check->setKey(substr($key, 0, $checkKeyLength));
$this->hmac_check_name = $mac_algorithm_in; $this->hmac_check_name = $mac_algorithm_in;
@ -2468,8 +2470,8 @@ class SSH2
// see http://tools.ietf.org/html/rfc4256#section-3.4 // see http://tools.ietf.org/html/rfc4256#section-3.4
$packet = $logged = pack('CN', MessageType::USERAUTH_INFO_RESPONSE, count($responses)); $packet = $logged = pack('CN', MessageType::USERAUTH_INFO_RESPONSE, count($responses));
for ($i = 0; $i < count($responses); $i++) { for ($i = 0; $i < count($responses); $i++) {
$packet.= Strings::packSSH2('s', $responses[$i]); $packet .= Strings::packSSH2('s', $responses[$i]);
$logged.= Strings::packSSH2('s', 'dummy-answer'); $logged .= Strings::packSSH2('s', 'dummy-answer');
} }
$this->send_binary_packet($packet, $logged); $this->send_binary_packet($packet, $logged);
@ -2536,7 +2538,7 @@ class SSH2
$privatekey = $privatekey->withPadding(RSA::SIGNATURE_PKCS1); $privatekey = $privatekey->withPadding(RSA::SIGNATURE_PKCS1);
$algos = ['rsa-sha2-256', 'rsa-sha2-512', 'ssh-rsa']; $algos = ['rsa-sha2-256', 'rsa-sha2-512', 'ssh-rsa'];
if (isset($this->preferred['hostkey'])) { if (isset($this->preferred['hostkey'])) {
$algos = array_intersect($this->preferred['hostkey'] , $algos); $algos = array_intersect($this->preferred['hostkey'], $algos);
} }
$algo = self::array_intersect_first($algos, $this->server_host_key_algorithms); $algo = self::array_intersect_first($algos, $this->server_host_key_algorithms);
switch ($algo) { switch ($algo) {
@ -2553,7 +2555,7 @@ class SSH2
$hash = 'sha1'; $hash = 'sha1';
$signatureType = 'ssh-rsa'; $signatureType = 'ssh-rsa';
} }
} else if ($publickey instanceof EC) { } elseif ($publickey instanceof EC) {
$privatekey = $privatekey->withSignatureFormat('SSH2'); $privatekey = $privatekey->withSignatureFormat('SSH2');
$curveName = $privatekey->getCurve(); $curveName = $privatekey->getCurve();
switch ($curveName) { switch ($curveName) {
@ -2579,7 +2581,7 @@ class SSH2
} }
throw new UnsupportedCurveException('Named Curve of ' . $curveName . ' is not supported by phpseclib3\'s SSH2 implementation'); throw new UnsupportedCurveException('Named Curve of ' . $curveName . ' is not supported by phpseclib3\'s SSH2 implementation');
} }
} else if ($publickey instanceof DSA) { } elseif ($publickey instanceof DSA) {
$privatekey = $privatekey->withSignatureFormat('SSH2'); $privatekey = $privatekey->withSignatureFormat('SSH2');
$hash = 'sha1'; $hash = 'sha1';
$signatureType = 'ssh-dss'; $signatureType = 'ssh-dss';
@ -2629,7 +2631,7 @@ class SSH2
if ($publickey instanceof RSA) { if ($publickey instanceof RSA) {
$signature = Strings::packSSH2('ss', $signatureType, $signature); $signature = Strings::packSSH2('ss', $signatureType, $signature);
} }
$packet.= Strings::packSSH2('s', $signature); $packet .= Strings::packSSH2('s', $signature);
$this->send_binary_packet($packet); $this->send_binary_packet($packet);
@ -2673,7 +2675,7 @@ class SSH2
* @param int $interval * @param int $interval
* @access public * @access public
*/ */
function setKeepAlive($interval) public function setKeepAlive($interval)
{ {
$this->keepAlive = $interval; $this->keepAlive = $interval;
} }
@ -2810,7 +2812,7 @@ class SSH2
return true; return true;
} }
} else { } else {
$output.= $temp; $output .= $temp;
} }
} }
} }
@ -3014,7 +3016,7 @@ class SSH2
return Strings::shift($this->interactiveBuffer, strlen($this->interactiveBuffer)); return Strings::shift($this->interactiveBuffer, strlen($this->interactiveBuffer));
} }
$this->interactiveBuffer.= $response; $this->interactiveBuffer .= $response;
} }
} }
@ -3299,11 +3301,11 @@ class SSH2
if (!@stream_select($read, $write, $except, $this->keepAlive)) { if (!@stream_select($read, $write, $except, $this->keepAlive)) {
$this->send_binary_packet(pack('CN', MessageType::IGNORE, 0)); $this->send_binary_packet(pack('CN', MessageType::IGNORE, 0));
$elapsed = microtime(true) - $start; $elapsed = microtime(true) - $start;
$this->curTimeout-= $elapsed; $this->curTimeout -= $elapsed;
return $this->get_binary_packet(true); return $this->get_binary_packet(true);
} }
$elapsed = microtime(true) - $start; $elapsed = microtime(true) - $start;
$this->curTimeout-= $elapsed; $this->curTimeout -= $elapsed;
} }
$sec = (int) floor($this->curTimeout); $sec = (int) floor($this->curTimeout);
@ -3315,7 +3317,7 @@ class SSH2
return true; return true;
} }
$elapsed = microtime(true) - $start; $elapsed = microtime(true) - $start;
$this->curTimeout-= $elapsed; $this->curTimeout -= $elapsed;
} }
} }
@ -3347,7 +3349,7 @@ class SSH2
* @var integer $packet_length * @var integer $packet_length
*/ */
$raw.= $this->read_remaining_bytes($packet_length - $this->decrypt_block_size + 4); $raw .= $this->read_remaining_bytes($packet_length - $this->decrypt_block_size + 4);
$stop = microtime(true); $stop = microtime(true);
$tag = stream_get_contents($this->fsock, $this->decrypt_block_size); $tag = stream_get_contents($this->fsock, $this->decrypt_block_size);
$this->decrypt->setTag($tag); $this->decrypt->setTag($tag);
@ -3370,7 +3372,7 @@ class SSH2
* @var integer $packet_length * @var integer $packet_length
*/ */
$raw.= $this->read_remaining_bytes($packet_length - $this->decrypt_block_size + 4); $raw .= $this->read_remaining_bytes($packet_length - $this->decrypt_block_size + 4);
$stop = microtime(true); $stop = microtime(true);
$tag = stream_get_contents($this->fsock, 16); $tag = stream_get_contents($this->fsock, 16);
@ -3398,7 +3400,7 @@ class SSH2
/** /**
* @var integer $packet_length * @var integer $packet_length
*/ */
$raw.= $this->read_remaining_bytes($packet_length - $this->decrypt_block_size + 4); $raw .= $this->read_remaining_bytes($packet_length - $this->decrypt_block_size + 4);
$stop = microtime(true); $stop = microtime(true);
$encrypted = $temp . $raw; $encrypted = $temp . $raw;
$raw = $temp . $this->decrypt->decrypt($raw); $raw = $temp . $this->decrypt->decrypt($raw);
@ -3426,7 +3428,7 @@ class SSH2
$stop = microtime(true); $stop = microtime(true);
} }
if (strlen($buffer)) { if (strlen($buffer)) {
$raw.= $this->decrypt ? $this->decrypt->decrypt($buffer) : $buffer; $raw .= $this->decrypt ? $this->decrypt->decrypt($buffer) : $buffer;
} }
$payload = Strings::shift($raw, $packet_length - $padding_length - 1); $payload = Strings::shift($raw, $packet_length - $padding_length - 1);
@ -3532,7 +3534,7 @@ class SSH2
case $this->decryptName == 'aes256-gcm@openssh.com': case $this->decryptName == 'aes256-gcm@openssh.com':
case $this->decryptName == 'chacha20-poly1305@openssh.com': case $this->decryptName == 'chacha20-poly1305@openssh.com':
case $this->hmac_check instanceof Hash && $this->hmac_check_etm: case $this->hmac_check instanceof Hash && $this->hmac_check_etm:
$remaining_length+= $this->decrypt_block_size - 4; $remaining_length += $this->decrypt_block_size - 4;
$adjustLength = true; $adjustLength = true;
} }
} }
@ -3551,7 +3553,7 @@ class SSH2
} }
if ($adjustLength) { if ($adjustLength) {
$remaining_length-= $this->decrypt_block_size - 4; $remaining_length -= $this->decrypt_block_size - 4;
} }
$buffer = ''; $buffer = '';
@ -3561,8 +3563,8 @@ class SSH2
$this->disconnect_helper(DisconnectReason::CONNECTION_LOST); $this->disconnect_helper(DisconnectReason::CONNECTION_LOST);
throw new \RuntimeException('Error reading from socket'); throw new \RuntimeException('Error reading from socket');
} }
$buffer.= $temp; $buffer .= $temp;
$remaining_length-= strlen($temp); $remaining_length -= strlen($temp);
} }
return $buffer; return $buffer;
@ -3714,7 +3716,7 @@ class SSH2
Strings::shift($payload, 1); Strings::shift($payload, 1);
list($channel, $window_size) = Strings::unpackSSH2('NN', $payload); list($channel, $window_size) = Strings::unpackSSH2('NN', $payload);
$this->window_size_client_to_server[$channel]+= $window_size; $this->window_size_client_to_server[$channel] += $window_size;
$payload = ($this->bitmap & self::MASK_WINDOW_ADJUST) ? true : $this->get_binary_packet($skip_channel_filter); $payload = ($this->bitmap & self::MASK_WINDOW_ADJUST) ? true : $this->get_binary_packet($skip_channel_filter);
} }
@ -3861,7 +3863,7 @@ class SSH2
// will not be setup yet on incoming channel open request // will not be setup yet on incoming channel open request
if (isset($channel) && isset($this->channel_status[$channel]) && isset($this->window_size_server_to_client[$channel])) { if (isset($channel) && isset($this->channel_status[$channel]) && isset($this->window_size_server_to_client[$channel])) {
$this->window_size_server_to_client[$channel]-= strlen($response); $this->window_size_server_to_client[$channel] -= strlen($response);
// resize the window, if appropriate // resize the window, if appropriate
if ($this->window_size_server_to_client[$channel] < 0) { if ($this->window_size_server_to_client[$channel] < 0) {
@ -3869,7 +3871,7 @@ class SSH2
//if ($this->window_size_server_to_client[$channel] < 0x3FFFFFFF) { //if ($this->window_size_server_to_client[$channel] < 0x3FFFFFFF) {
$packet = pack('CNN', MessageType::CHANNEL_WINDOW_ADJUST, $this->server_channels[$channel], $this->window_resize); $packet = pack('CNN', MessageType::CHANNEL_WINDOW_ADJUST, $this->server_channels[$channel], $this->window_resize);
$this->send_binary_packet($packet); $this->send_binary_packet($packet);
$this->window_size_server_to_client[$channel]+= $this->window_resize; $this->window_size_server_to_client[$channel] += $this->window_resize;
} }
switch ($type) { switch ($type) {
@ -3881,7 +3883,7 @@ class SSH2
*/ */
// currently, there's only one possible value for $data_type_code: NET_SSH2_EXTENDED_DATA_STDERR // currently, there's only one possible value for $data_type_code: NET_SSH2_EXTENDED_DATA_STDERR
list($data_type_code, $data) = Strings::unpackSSH2('Ns', $response); list($data_type_code, $data) = Strings::unpackSSH2('Ns', $response);
$this->stdErrorLog.= $data; $this->stdErrorLog .= $data;
if ($skip_extended || $this->quiet_mode) { if ($skip_extended || $this->quiet_mode) {
continue 2; continue 2;
} }
@ -3907,7 +3909,7 @@ class SSH2
$this->errors[] = "SSH_MSG_CHANNEL_REQUEST (exit-signal): $signal_name"; $this->errors[] = "SSH_MSG_CHANNEL_REQUEST (exit-signal): $signal_name";
if (strlen($error_message)) { if (strlen($error_message)) {
$this->errors[count($this->errors) - 1].= "\r\n$error_message"; $this->errors[count($this->errors) - 1] .= "\r\n$error_message";
} }
$this->send_binary_packet(pack('CN', MessageType::CHANNEL_EOF, $this->server_channels[$client_channel])); $this->send_binary_packet(pack('CN', MessageType::CHANNEL_EOF, $this->server_channels[$client_channel]));
@ -3941,8 +3943,8 @@ class SSH2
) = Strings::unpackSSH2('NNN', $response); ) = Strings::unpackSSH2('NNN', $response);
if ($window_size < 0) { if ($window_size < 0) {
$window_size&= 0x7FFFFFFF; $window_size &= 0x7FFFFFFF;
$window_size+= 0x80000000; $window_size += 0x80000000;
} }
$this->window_size_client_to_server[$channel] = $window_size; $this->window_size_client_to_server[$channel] = $window_size;
$result = $client_channel == $channel ? true : $this->get_channel_packet($client_channel, $skip_extended); $result = $client_channel == $channel ? true : $this->get_channel_packet($client_channel, $skip_extended);
@ -4010,7 +4012,7 @@ class SSH2
$this->curTimeout = 5; $this->curTimeout = 5;
if ($this->bitmap & self::MASK_SHELL) { if ($this->bitmap & self::MASK_SHELL) {
$this->bitmap&= ~self::MASK_SHELL; $this->bitmap &= ~self::MASK_SHELL;
} }
if ($this->channel_status[$channel] != MessageType::CHANNEL_EOF) { if ($this->channel_status[$channel] != MessageType::CHANNEL_EOF) {
$this->send_binary_packet(pack('CN', MessageType::CHANNEL_CLOSE, $this->server_channels[$channel])); $this->send_binary_packet(pack('CN', MessageType::CHANNEL_CLOSE, $this->server_channels[$channel]));
@ -4072,17 +4074,17 @@ class SSH2
// 4 (packet length) + 1 (padding length) + 4 (minimal padding amount) == 9 // 4 (packet length) + 1 (padding length) + 4 (minimal padding amount) == 9
$packet_length = strlen($data) + 9; $packet_length = strlen($data) + 9;
if ($this->encrypt && $this->encrypt->usesNonce()) { if ($this->encrypt && $this->encrypt->usesNonce()) {
$packet_length-= 4; $packet_length -= 4;
} }
// round up to the nearest $this->encrypt_block_size // round up to the nearest $this->encrypt_block_size
$packet_length+= (($this->encrypt_block_size - 1) * $packet_length) % $this->encrypt_block_size; $packet_length += (($this->encrypt_block_size - 1) * $packet_length) % $this->encrypt_block_size;
// subtracting strlen($data) is obvious - subtracting 5 is necessary because of packet_length and padding_length // subtracting strlen($data) is obvious - subtracting 5 is necessary because of packet_length and padding_length
$padding_length = $packet_length - strlen($data) - 5; $padding_length = $packet_length - strlen($data) - 5;
switch (true) { switch (true) {
case $this->encrypt && $this->encrypt->usesNonce(): case $this->encrypt && $this->encrypt->usesNonce():
case $this->hmac_create instanceof Hash && $this->hmac_create_etm: case $this->hmac_create instanceof Hash && $this->hmac_create_etm:
$padding_length+= 4; $padding_length += 4;
$packet_length+= 4; $packet_length += 4;
} }
$padding = Random::string($padding_length); $padding = Random::string($padding_length);
@ -4154,7 +4156,7 @@ class SSH2
$this->send_seq_no++; $this->send_seq_no++;
$packet.= $this->encrypt && $this->encrypt->usesNonce() ? $this->encrypt->getTag() : $hmac; $packet .= $this->encrypt && $this->encrypt->usesNonce() ? $this->encrypt->getTag() : $hmac;
$start = microtime(true); $start = microtime(true);
$sent = @fputs($this->fsock, $packet); $sent = @fputs($this->fsock, $packet);
@ -4208,10 +4210,10 @@ class SSH2
// the most useful log for SSH2 // the most useful log for SSH2
case self::LOG_COMPLEX: case self::LOG_COMPLEX:
$this->message_number_log[] = $message_number; $this->message_number_log[] = $message_number;
$this->log_size+= strlen($message); $this->log_size += strlen($message);
$this->message_log[] = $message; $this->message_log[] = $message;
while ($this->log_size > self::LOG_MAX_SIZE) { while ($this->log_size > self::LOG_MAX_SIZE) {
$this->log_size-= strlen(array_shift($this->message_log)); $this->log_size -= strlen(array_shift($this->message_log));
array_shift($this->message_number_log); array_shift($this->message_number_log);
} }
break; break;
@ -4248,10 +4250,10 @@ class SSH2
$entry = $this->format_log([$message], [$message_number]); $entry = $this->format_log([$message], [$message_number]);
if ($this->realtime_log_wrap) { if ($this->realtime_log_wrap) {
$temp = "<<< START >>>\r\n"; $temp = "<<< START >>>\r\n";
$entry.= $temp; $entry .= $temp;
fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp)); fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp));
} }
$this->realtime_log_size+= strlen($entry); $this->realtime_log_size += strlen($entry);
if ($this->realtime_log_size > self::LOG_MAX_SIZE) { if ($this->realtime_log_size > self::LOG_MAX_SIZE) {
fseek($this->realtime_log_file, 0); fseek($this->realtime_log_file, 0);
$this->realtime_log_size = strlen($entry); $this->realtime_log_size = strlen($entry);
@ -4275,10 +4277,10 @@ class SSH2
{ {
while (strlen($data)) { while (strlen($data)) {
if (!$this->window_size_client_to_server[$client_channel]) { if (!$this->window_size_client_to_server[$client_channel]) {
$this->bitmap^= self::MASK_WINDOW_ADJUST; $this->bitmap ^= self::MASK_WINDOW_ADJUST;
// using an invalid channel will let the buffers be built up for the valid channels // using an invalid channel will let the buffers be built up for the valid channels
$this->get_channel_packet(-1); $this->get_channel_packet(-1);
$this->bitmap^= self::MASK_WINDOW_ADJUST; $this->bitmap ^= self::MASK_WINDOW_ADJUST;
} }
/* The maximum amount of data allowed is determined by the maximum /* The maximum amount of data allowed is determined by the maximum
@ -4297,7 +4299,7 @@ class SSH2
$this->server_channels[$client_channel], $this->server_channels[$client_channel],
$temp $temp
); );
$this->window_size_client_to_server[$client_channel]-= strlen($temp); $this->window_size_client_to_server[$client_channel] -= strlen($temp);
$this->send_binary_packet($packet); $this->send_binary_packet($packet);
} }
@ -4342,7 +4344,7 @@ class SSH2
} }
if ($this->bitmap & self::MASK_SHELL) { if ($this->bitmap & self::MASK_SHELL) {
$this->bitmap&= ~self::MASK_SHELL; $this->bitmap &= ~self::MASK_SHELL;
} }
} }
@ -4408,12 +4410,12 @@ class SSH2
{ {
$output = ''; $output = '';
for ($i = 0; $i < count($message_log); $i++) { for ($i = 0; $i < count($message_log); $i++) {
$output.= $message_number_log[$i] . "\r\n"; $output .= $message_number_log[$i] . "\r\n";
$current_log = $message_log[$i]; $current_log = $message_log[$i];
$j = 0; $j = 0;
do { do {
if (strlen($current_log)) { if (strlen($current_log)) {
$output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 '; $output .= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 ';
} }
$fragment = Strings::shift($current_log, $this->log_short_width); $fragment = Strings::shift($current_log, $this->log_short_width);
$hex = substr(preg_replace_callback('#.#s', function ($matches) { $hex = substr(preg_replace_callback('#.#s', function ($matches) {
@ -4423,10 +4425,10 @@ class SSH2
// http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
// also replace < with a . since < messes up the output on web browsers // also replace < with a . since < messes up the output on web browsers
$raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment); $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment);
$output.= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n"; $output .= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n";
$j++; $j++;
} while (strlen($current_log)); } while (strlen($current_log));
$output.= "\r\n"; $output .= "\r\n";
} }
return $output; return $output;
@ -5102,7 +5104,7 @@ class SSH2
return self::$connections; return self::$connections;
} }
$temp = []; $temp = [];
foreach (self::$connections as $key=>$ref) { foreach (self::$connections as $key => $ref) {
$temp[$key] = $ref->get(); $temp[$key] = $ref->get();
} }
return $temp; return $temp;

View File

@ -267,7 +267,7 @@ class Agent
public function forwardData($data) public function forwardData($data)
{ {
if ($this->expected_bytes > 0) { if ($this->expected_bytes > 0) {
$this->socket_buffer.= $data; $this->socket_buffer .= $data;
$this->expected_bytes -= strlen($data); $this->expected_bytes -= strlen($data);
} else { } else {
$agent_data_bytes = current(unpack('N', $data)); $agent_data_bytes = current(unpack('N', $data));

View File

@ -9,6 +9,7 @@
* *
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
*/ */
if (extension_loaded('mbstring')) { if (extension_loaded('mbstring')) {
// 2 - MB_OVERLOAD_STRING // 2 - MB_OVERLOAD_STRING
// mbstring.func_overload is deprecated in php 7.2 and removed in php 8.0. // mbstring.func_overload is deprecated in php 7.2 and removed in php 8.0.

View File

@ -11,10 +11,10 @@ use phpseclib3\Net\SFTP\FileType;
class Functional_Net_SFTPUserStoryTest extends PhpseclibFunctionalTestCase class Functional_Net_SFTPUserStoryTest extends PhpseclibFunctionalTestCase
{ {
static protected $scratchDir; protected static $scratchDir;
static protected $exampleData; protected static $exampleData;
static protected $exampleDataLength; protected static $exampleDataLength;
static protected $buffer; protected static $buffer;
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
@ -136,7 +136,7 @@ class Functional_Net_SFTPUserStoryTest extends PhpseclibFunctionalTestCase
return $sftp; return $sftp;
} }
static function demoCallback($length) public static function demoCallback($length)
{ {
$r = substr(self::$buffer, 0, $length); $r = substr(self::$buffer, 0, $length);
self::$buffer = substr(self::$buffer, $length); self::$buffer = substr(self::$buffer, $length);
@ -487,6 +487,7 @@ class Functional_Net_SFTPUserStoryTest extends PhpseclibFunctionalTestCase
/** /**
* on older versions this would result in a fatal error * on older versions this would result in a fatal error
*
* @depends testStatOnCWD * @depends testStatOnCWD
* @group github402 * @group github402
*/ */
@ -765,7 +766,14 @@ class Functional_Net_SFTPUserStoryTest extends PhpseclibFunctionalTestCase
$list_cache_disabled = $sftp->rawlist('.', true); $list_cache_disabled = $sftp->rawlist('.', true);
$this->assertEquals($list_cache_enabled, $list_cache_disabled, 'The files should be the same regardless of stat cache', 0.0, 10, true); $this->assertEquals(
$list_cache_enabled,
$list_cache_disabled,
'The files should be the same regardless of stat cache',
0.0,
10,
true
);
return $sftp; return $sftp;
} }

View File

@ -15,7 +15,7 @@ class SFTPWrongServerTest extends TestCase
// getaddrinfo message seems not to return stable text // getaddrinfo message seems not to return stable text
static::assertSame( static::assertSame(
'Cannot connect to dummy-server:22. Error 0. php_network_getaddresses: getaddrinfo', 'Cannot connect to dummy-server:22. Error 0. php_network_getaddresses: getaddrinfo',
substr($e->getMessage(),0,81) substr($e->getMessage(), 0, 81)
); );
} }
} }

View File

@ -24,7 +24,7 @@ class Functional_Net_SSH2AgentTest extends PhpseclibFunctionalTestCase
public function testAgentLogin() public function testAgentLogin()
{ {
$ssh = new SSH2($this->getEnv('SSH_HOSTNAME')); $ssh = new SSH2($this->getEnv('SSH_HOSTNAME'));
$agent = new Agent; $agent = new Agent();
$this->assertTrue( $this->assertTrue(
$ssh->login($this->getEnv('SSH_USERNAME'), $agent), $ssh->login($this->getEnv('SSH_USERNAME'), $agent),

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Andreas Fischer <bantu@phpbb.com> * @author Andreas Fischer <bantu@phpbb.com>
* @copyright 2014 Andreas Fischer * @copyright 2014 Andreas Fischer

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Andreas Fischer <bantu@phpbb.com> * @author Andreas Fischer <bantu@phpbb.com>
* @copyright 2013 Andreas Fischer * @copyright 2013 Andreas Fischer

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Andreas Fischer <bantu@phpbb.com> * @author Andreas Fischer <bantu@phpbb.com>
* @copyright 2013 Andreas Fischer * @copyright 2013 Andreas Fischer

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Andreas Fischer <bantu@phpbb.com> * @author Andreas Fischer <bantu@phpbb.com>
* @copyright 2013 Andreas Fischer * @copyright 2013 Andreas Fischer

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Andreas Fischer <bantu@phpbb.com> * @author Andreas Fischer <bantu@phpbb.com>
* @copyright 2013 Andreas Fischer * @copyright 2013 Andreas Fischer

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Andreas Fischer <bantu@phpbb.com> * @author Andreas Fischer <bantu@phpbb.com>
* @copyright 2013 Andreas Fischer * @copyright 2013 Andreas Fischer

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Andreas Fischer <bantu@phpbb.com> * @author Andreas Fischer <bantu@phpbb.com>
* @copyright 2013 Andreas Fischer * @copyright 2013 Andreas Fischer
@ -188,7 +189,7 @@ abstract class Unit_Crypt_AES_TestCase extends PhpseclibTestCase
$result = ''; $result = '';
foreach ($test as $len) { foreach ($test as $len) {
$temp = str_repeat('d', $len); $temp = str_repeat('d', $len);
$str.= $temp; $str .= $temp;
} }
$c1 = $aes->$op($str); $c1 = $aes->$op($str);
@ -204,7 +205,7 @@ abstract class Unit_Crypt_AES_TestCase extends PhpseclibTestCase
foreach ($test as $len) { foreach ($test as $len) {
$temp = str_repeat('d', $len); $temp = str_repeat('d', $len);
$output = $aes->$op($temp); $output = $aes->$op($temp);
$result.= $output; $result .= $output;
} }
$c2 = $result; $c2 = $result;
@ -237,7 +238,7 @@ abstract class Unit_Crypt_AES_TestCase extends PhpseclibTestCase
$result = ''; $result = '';
foreach ($test as $len) { foreach ($test as $len) {
$temp = str_repeat('d', $len); $temp = str_repeat('d', $len);
$str.= $temp; $str .= $temp;
} }
$c1 = $aes->$op($str); $c1 = $aes->$op($str);
@ -252,7 +253,7 @@ abstract class Unit_Crypt_AES_TestCase extends PhpseclibTestCase
foreach ($test as $len) { foreach ($test as $len) {
$temp = str_repeat('d', $len); $temp = str_repeat('d', $len);
$output = $aes->$op($temp); $output = $aes->$op($temp);
$result.= $output; $result .= $output;
} }
$c2 = $result; $c2 = $result;

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Andreas Fischer <bantu@phpbb.com> * @author Andreas Fischer <bantu@phpbb.com>
* @copyright MMXIII Andreas Fischer * @copyright MMXIII Andreas Fischer

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2014 Jim Wigginton * @copyright 2014 Jim Wigginton
@ -92,7 +93,7 @@ class Unit_Crypt_ChaCha20Test extends PhpseclibTestCase
$expected = str_replace(':', '', $expected); $expected = str_replace(':', '', $expected);
$expected = pack('H*', $expected); $expected = pack('H*', $expected);
$c = new ChaCha20; $c = new ChaCha20();
$c->setPoly1305Key($key); $c->setPoly1305Key($key);
$r = new \ReflectionClass(get_class($c)); $r = new \ReflectionClass(get_class($c));
// this unit test is testing Poly1305 independent of ChaCha20, which phpseclib doesn't // this unit test is testing Poly1305 independent of ChaCha20, which phpseclib doesn't
@ -209,7 +210,7 @@ class Unit_Crypt_ChaCha20Test extends PhpseclibTestCase
$p1 = $c->encrypt($plaintext); $p1 = $c->encrypt($plaintext);
$p2 = ''; $p2 = '';
foreach ($partitions as $partition) { foreach ($partitions as $partition) {
$p2.= $c2->encrypt(str_repeat("\0", $partition)); $p2 .= $c2->encrypt(str_repeat("\0", $partition));
} }
$this->assertSame($p1, $p2, "Failed asserting that ciphertext matches expected value with $engine engine"); $this->assertSame($p1, $p2, "Failed asserting that ciphertext matches expected value with $engine engine");

Some files were not shown because too many files have changed in this diff Show More